关于javascript:原型与原型链

6次阅读

共计 863 个字符,预计需要花费 3 分钟才能阅读完成。

原型分为显示原型(prototype)隐式原型(__proto__)。
其对应的原型关系如下:
1. 每个 class 都有显示原型 prototype。
2. 每个对象实例都有一个隐式原型__proto__指向对应的 class 的 prototype。
3. 对象实例的__proto__指向对应的 class 的 prototype。

基于原型的执行规定
获取属性 xialuo.name 或者执行办法 xialuo。sayHi()时:
1. 先在本身属性和办法寻找。
2. 如果找不到则主动去__proto__中查找,若始终往上查找到 Object 这个顶级对象仍未找到,则返回 Object.prototype.__proto__下的值为 null。

什么是原型链?
答:每个实例对象(object)都有一个公有属性(__proto__)指向它的构造函数的原型对象(prototype)。该原型对象也有一个本人的原型对象(__proto__),层层向上直到一个对象的原型对象为 null。由此造成的链式构造称为原型链。

其图示如下所示:

其对应代码如下所示:

class Person{constructor(name, number){
     this.name = name;
     this.number = number;
   }
    eat(){}
};
class Student extends Person{constructor(name, number){super(name, number)
   }
    sayHi(){}
}

let xialuo = new Student();

// 其关系如下:xialuo.__proto__ = Student.prototype;
console.log(xiaoluo.hasOwnProperty("name") )//true
console.log(xiaoluo.hasOwnProperty("eat") )//false
xialuo.instanceof Student //true
xialuo.instanceof Person //true
xialuo.instanceof Object //true
正文完
 0