阿孜去面试-原型与原型链

231 阅读1分钟

JS的尽头是Null,人类的终点是什么?

Petal_splash.jpg >> 原型链是什么

<< 实例和原型之间构造的一条链。我理解为,一张桌子,桌子的原型是木头,木头又是树做的。。。一直到原子分子。但这样会不会有问题呢,js原型链的终点是null,我们所在的世界却看不到终点。

function SuperType() {
  this.property = true;
}
let instance = new SuperType();
console.log(instance); // 包含{property:true,[[Prototype]]:{constructor:superType(),[[Prototype]]:Object}}

// Supertype -> Function.prototype -> Object.prototype -> null

function SuperType() {
  this.property = true;
}
SuperType.prototype.getSuperValue = function () {
  return this.property;
};

function SubType() {
  this.subproperty;
}
SubType.prototype = new SuperType();

let instance = new SubType();
console.log(instance); // 包含{[[Prototype]]:{property:true,[[Prototype]]:{getSuperValue:function,constructor:superType(),[[Prototype]]:Object}}}

// SubType -> Supertype.prototype -> Function.prototype ->  Object.prototype -> null
console.log(instance.getSuperValue()); // true

console.log(SuperType.prototype.isPrototypeOf(instance)) // true


function SuperType() {
  this.property = true;
}
SuperType.prototype.getSuperValue = function () {
  return this.property;
};
SuperType.prototype.property = 123;

SuperType.prototype.__proto__ = null;

let instance = new SuperType();
console.log(instance); // 包含{property:true,[[Prototype]]:{getSuperValue:function,constructor:superType()}}

// Supertype -> Function.prototype -> null

console.log(instance.getSuperValue()); // true 先找当前再找原型上的

console.log(instance instanceof SuperType) // true
console.log(SuperType.prototype.isPrototypeOf(instance)) // error 这个被我清了