原型&原型链

110 阅读1分钟

prototype

  • 只有函数(包括构造函数)才有 prototype 属性(箭头函数除外)
  • prototype 属性主要用于实现原型继承与共享属性和方法
// 函数有 prototype
function Person() {}
Person.prototype.name = "张三";
console.log(Person.prototype.name); // "张三"

// 普通对象没有 prototype
const obj = {};
console.log(obj.prototype); // undefined

// 验证原型是否为 Person.prototype
const person = new Person();
console.log(Object.getPrototypeOf(person) === Person.prototype ); // true

image.png

proto

  • 所有对象(包括函数)都有 __proto__属性 (这个属性会指向该对象的原型prototype
function Person() {

}
var person = new Person();

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

image.png

constructor

constructor 是 JavaScript 对象的一个属性,它指向创建该对象的构造函数

function Person() {

}

var person = new Person();

// person是构造函数Person的实例化对象,所以实例对象person通过__proto__可以找到实例原型Person.prototype
console.log(person.__proto__ == Person.prototype) // true

// 实例原型Person.prototype通过constructor可以找到构造函数Person
console.log(Person.prototype.constructor == Person) // true

// Object.getPrototypeOf(person) 方法返回实例对象的原型
console.log(Object.getPrototypeOf(person) === Person.prototype) // true

image.png

原型链

当访问一个对象的属性或方法时,如果该对象本身没有,JavaScript 会沿着 __proto__ 向上查找,直到找到 Object.prototype(最终是 null)。 这种链式查找的过程就是 原型链

console.log(Object.prototype.__proto__ === null) // true

image.png