概念说明
prototype和__proto__均为函数中的一种属性,区别在于prototype
是构造函数的属性,用于定义实例共享的属性和方法,__proto__
是实例的属性,指向创建它的构造函数的prototype
function Animal(type) {
this.type = type;
}
// 为构造函数的prototype添加方法
Animal.prototype.speak = function() {
console.log(`I'm a ${this.type}`);
};
// 创建实例
const dog = new Animal('dog');
const cat = new Animal('cat');
// 验证实例的__proto__指向构造函数的prototype
console.log(dog.__proto__ === Animal.prototype); // true
console.log(cat.__proto__ === Animal.prototype); // true
// 验证构造函数的prototype.constructor指向自身
console.log(Animal.prototype.constructor === Animal); // true
// 实例继承的方法来自prototype
console.log(dog.speak === Animal.prototype.speak); // true
console.log(cat.speak === Animal.prototype.speak); // true
原型链的层级结构
const bird = new Animal('bird');
// 验证原型链的层级
console.log(bird.__proto__ === Animal.prototype); // true
console.log(Animal.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__ === null); // true(原型链终点)
// 通过原型链访问Object的方法
console.log(bird.toString === Object.prototype.toString); // true
console.log(bird.hasOwnProperty === Object.prototype.hasOwnProperty); // true
改原型对实例的影响
function Fruit(name) {
this.name = name;
}
const apple = new Fruit('apple');
const banana = new Fruit('banana');
// 修改原型前
console.log(apple.color); // undefined
// 向原型添加属性
Fruit.prototype.color = 'unknown';
// 验证所有实例继承新属性
console.log(apple.color);
console.log(banana.color);
console.log(apple.color === Fruit.prototype.color); // true