# 原型链继承
function Parent() {
this.name = 'p';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
# 构造函数继承
function Child1() {
Parent.call(this, 'p');
# 组合式继承
function Parent2(name) {
this.name = [name];
}
Parent.prototype.getName = function() {
return this.name;
};
function Child2() {
// 构造函数继承
Parent2.call(this, 'zhangsan');
}
# 原型链继承
Child2.prototype = new Parent2();
Child2.prototype.constructor = Child2;
# 寄生式组合继承
function Parent3(name) {
this.name = [name];
}
Parent.prototype.getName = function() {
return this.name;
};
function Child3() {
// 构造函数继承
Parent3.call(this, 'zhangsan');
}
# 原型链继承
// Child3.prototype = new Parent();
Child3.prototype = Object.create(Parent.prototype) ; //将`指向父类实例`改为`指向父类原型`
Child3.prototype.constructor = Child3;
//测试
const child1 = new Child();
const child2 = new Child();
child1.name[0] = 'foo';
console.log(child1.name); // ['foo']
console.log(child2.name); // ['zhangsan']
child2.getName(); // ['zhangsan']