原型链继承
// 父类构造函数
function Parent() {
this.name = 'John';
this.habits = ['basketball', 'cook', 'boxing'];
}
// 父类原型
Parent.prototype.sayHello = function sayHello() {
console.log('hello, world');
}
// 子类构造函数
function Child() {
// @empty
}
// 将子类的原型指向父类的一个实例
Child.prototype = new Parent();
const child_1 = new Child();
console.log(child_1.name); // John
console.log(child_2.habits); // ['basketball', 'cook', 'boxing']
const child_2 = new Child();
console.log(child_1.habits === child_2.habits); // true
child_1.habits.push('running');
console.log(child_1.habits); // ['basketball', 'cook', 'boxing', 'running']
缺点:父类实例中的引用类型对象由所有的子类实例共享,只要其中一个子类实例对其进行了修改,便会影响其他子类实例,容易“牵一发动全身”,造成容易忽略的BUG.
构造函数继承
function Parent(name) {
this.name = name;
this.habits = ['boxing'];
this.sayHello = function sayHello() {
console.log('hello, world!');
}
}
function Child() {
Parent.call(this, 'frank');
}
const child_1 = new Child();
const child_2 = new Child();
child_1.habits.push('cooking');
console.log(child_1.habits); // ['boxing', 'cooking']
console.log(child_2.habits); // ['boxing']
console.log(child_1.sayHello === child_2.sayHello); // false