这是我根据 红宝石书 得到的几种方式
/**
* 组合式继承
* 缺点 两次调用父类的构造函数 效率比较低
*
*/
function SuperType(name) {
this.name = name
this.colors = ['red', 'blue', 'green']
}
SuperType.prototype.sayName = function() {
console.log(this.name)
}
function SubType(name, age) {
// 第二次调用 会在其实例上添加 name、colors属性
// 所以访问时 访问的是其实例上的属性 从而将其原型上的属性屏蔽了
SuperType.call(this, name)
this.age = age
}
// 第一次调用 会在 SubType 的原型上添加 name 、colors属性
SubType.prototype = new SuperType()
SubType.prototype.sayAge = function() {
console.log(this.age)
}
let instance1 = new SubType("Nicholas", 23);
instance1.colors.push("black");
console.log(instance1, 'instance1')
let instance2 = new SubType("Greg", 11);
console.log(instance2, 'instance2');
/*
* 原型式继承
* 缺点 引用数据类型存在共享的问题
*/
function objPrototype(obj) {
function F() {}
F.prototype = obj
return new F()
}
let per = {
name: 'xc',
friends: ['Shelby', 'court', 'van']
}
let anotherPerson = objPrototype(per)
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
let yetAnotherPerson = objPrototype(per);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
console.log(per.friends) // ["Shelby", "court", "van", "Rob", "Barbie"]
// 可采用 Object.create()
let anotherPersonObj = Object.create(per, {
name: {
value: 'hhh'
}
})
/**
* 寄生式继承
* 缺点 方法挂载到实例上 占内存
*/
function createAnother(obj) {
let clone = Object(obj)
clone.sayHi = function() {
console.log('这是实例上的方法')
}
return clone
}
let perJs = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
}
let anotherPersonJs = createAnother(perJs)
anotherPersonJs.sayHi()
console.log(anotherPersonJs, '寄生式继承')
/**
* 寄生组合式继承 官方推荐
* 优点 引用数据不共享 只调用一次父类的构造函数
*/
function inheritPrototype(subType, superType) {
// subType 子类 superType 父类
let prototype = Object(superType.prototype)
prototype.constructor = subType
subType.prototype = prototype
}
function SuperType1(name) {
this.name = name
this.colors = ['blue', 'red']
}
SuperType1.prototype.sayName = function() {
console.log(this.name)
}
function SubType1(name, age) {
SuperType1.call(this, name)
this.age = age
}
inheritPrototype(SubType1, SuperType1)
SubType.prototype.sayAge = function(){
alert(this.age);
}
let sub = new SubType1('xc', 23)
console.log(sub,'寄生组合式继承')