24.JavaScript原型链的应用

1.获取对象的隐式原型

Object.getPrototypeOf(对象) === 对象.__proto__

2.判断当前对象(this)是否在指定对象的原型链上

Object.prototype.isPrototypeOf(对象)

判断是不是真数组:

Array.prototype.isPrototypeOf([]);

Array.isArray([]);

3.判断函数的原型是否在对象的原型链上

对象 instanceof 函数(不推荐使用)

4.创建一个新对象,该新对象的隐式原型指向指定的对象

Object.create(对象)

var obj = Object.create(Object.prototype);

obj.__proto__ === Object.prototype

5.判断一个对象自身是否拥有某个属性

Object.prototype.hasOwnProperty(属性名);

for(var prop in obj){

  if(obj.hasOwnProperty(prop)){//遍历属性的时候,不需要把原型链上的属性遍历

  }

}

应用:

1.类数组转换为真数组

Array.prototype.slice.call(类数组);

[].slice.call(类数组);

2.实现继承

this.myPlugin = this.myPlugin || {};

/**
 * 子类继承父类实现方式一
 */
this.myPlugin.inherit = function (son, father) {
    son.prototype = Object.create(father.prototype);
    son.prototype.constructor = son;
    son.prototype.uber = father.prototype;
}

/**
 * 子类继承父类实现方式二
 */
this.myPlugin.inherit = (function (son, father) {
    var Temp = function () {};
    return function (son, father) {
        Temp.prototype = father.prototype;
        son.prototype = new Temp();
        son.prototype.constructor = son;
        son.prototype.uber = father.prototype;
    }
}());
myPlugin.js

调用继承:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./js/myPlugin.js"></script>
    <script>
        function User(firstName, lastName, age){
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }
        User.prototype.sayHello = function(){
            console.log(`我叫${this.firstName}${this.lastName},今年${this.age}岁了`);
        }

        function VIPUser(firstName, lastName, age, money){
            User.call(this, firstName, lastName, age);
            this.money = money;
        }
        //VIPUser继承自User
        myPlugin.inherit(VIPUser, User);
        VIPUser.prototype.recharge = function(money){
            this.money += money;
        }
        var user = new User("", "", "19");
        var vip = new VIPUser("", "", "18", "500");
        
        vip.sayHello();
        console.log(user);
        console.log(vip);
    </script>
</body>
</html>
index.html

效果展示:

原文地址:https://www.cnblogs.com/lanshanxiao/p/12822813.html