JavaScript 原型 & 原型链 instanceof

164 阅读1分钟

蓝色为原型链

image.png

原型

  • 每一个对象(除了 null )都

    • 具有的一个属性,叫__proto__,它指向该对象的原型

    • 会从原型"继承"属性

    • prototype是函数才会有的属性

  • 每个原型都有一个 constructor 属性指向关联的构造函数

  • 当使用 obj.__proto__ 时,可以理解成返回了 Object.getPrototypeOf(obj)

function Person() {

}

var person = new Person()

console.log(person.__proto__ == Person.prototype) // true

console.log(Person.prototype.constructor == Person) // true

console.log(Object.getPrototypeOf(person) === Person.prototype) // true

console.log(person.constructor === Person) // true

原型链

  • Object.prototype 没有原型
console.log(Object.prototype.__proto__ === null) // true

构造函数

  • 构造的新对象内部有一个属性 prototype => 值是一个对象

    => 包含了共享的属性和方法

  • 使用构造函数创建对象后,被创建对象内部会存在一个指针proto => 指向构造函数 prototype 属性的对应值

链式获取属性规则

  • 对象的属性

  • => 对象内部本身是否包含该属性

  • => 顺着指针去原型对象里查找

  • => 在向上层级里去查找

instanceof

2 instanceof Number  // true
[] instanceOf Array   // true

instanceof 的原理实现

// 通过翻户口本,查家庭信息
function myInstance(left, right) {
  // 获取对象的原型
  let _proto = Object.getPrototypeOf(left)
  // 构造函数的prototype
  let _prototype = right.prototype

  while (true) {
    if (!_proto) {
      return false
    }

    if (_proto === _prototype) {
      return true
    }

    _proto = Object.getPrototypeOf(_proto)
  }
}
myInstance(2, Number)

继承方式?*