直接上代码
function Animal() {
this.colors = ['black', 'white']
}
Animal.prototype.getColor = function() {
return this.colors
}
function Dog() {}
Dog.prototype = new Animal()
let dog1 = new Dog()
dog1.colors.push('brown')
let dog2 = new Dog()
console.log(dog2.colors) // ['black', 'white', 'brown']
看图解析
- 红色线为原型链
总结:
- 将A构造函数的实例对象赋值给B构造函数的prototype, 即可实现B构造函数的实例对象继承了A构造函数的原型