这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战
同时继承多个对象
child6.prototype = Object.assign(child6.prototype,parent.prototype,parent2.prototype,parent3.prototype) child6.prototype.constructor = child6 Object.assign(target,source,..) 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
function Parent2() {
this.parent2Name = "parent2"
}
Parent2.prototype.say2=function () {
console.log("hi parent2")
}
function Parent3() {
this.parent3Name = "parent3"
}
Parent3.prototype.say3=function () {
console.log("hi,parent3")
}
function child6(name) {
Parent.call(this)
Parent2.call(this)
Parent3.call(this)
this.name = name
}
child6.prototype = Object.create(Object.assign(child6.prototype,Parent.prototype,Parent2.prototype,Parent3.prototype))
child6.prototype.constructor = child6
child6.prototype.c6 = "c6"
let c6 = new child6("c6")
console.log(c6)
原型式继承
- 原型式继承首先在obj()函数内部创建一个临时性的构造函数 ,然后将传入的对象作为这个构造函数的原型,最后返回这个临时类型的一个新实例。ES5提供了Object.create()函数,内部就是原型式继承
- 缺点:1)原型上的引用属性被所有实例共享,一个实例修改,其他的实例的原型上的引用属性也变了
2)无法传参,parent的属性值一开始就定了
function obj(o){
function F(){}
F.prototype = o;
return new F()
}
var parent = {
name:"tom",
age:22,
arr:[]
}
var c8 = obj(parent)
var c9 = obj(parent)
寄生式继承
实现的本质: 给原型式继承穿了个马甲而已,看起来比较像继承。同样是基于某个对象或某个信息创建一个对象,然后增强对象,最后返回对象。 缺点:同原型式继承
function create(o){
var f= obj(o);//o的属性会在对象的原型对象身上
f.run = function () {//增强对象,该属性会在对象的身上
return this.arr;
};
f.c_age = "c_age"//增强对象,该属性会在对象的身上
return f;
}
var c11 = create(parent)
console.log(c11)
寄生组合式继承
结合借用构造函数传递参数和寄生模式实现继承 优点:解决了组合继承的缺点,只调用了一次父类构造函数,避免了在子类构造函数的原型上创建不必要的、多余的属性。 缺点:理论上没有
这是最成熟的方法,也是现在库实现的方法
function Child12(c_age){
Parent.call(this,"child12",13)//获得父类构造函数的属性和方法,支持传参
this.c_age = c_age
}
function initPrototype(parent,child) {
//pro.__proto__==Parent.protype
let pro = Object.create(Parent.prototype)
pro.constructor = parent
child.prototype = pro//获得父类原型的属性和方法
}
//继承父类原型属性和方法
initPrototype(Parent,Child12)
// 新增子类原型属性,一定要在上面方法的后面新增自己的原型方法
Child12.prototype.sayChild=function(){
console.log("child prototype function")
}
var c12 = new Child12(222)
var c13 = new Child12(333)
console.log(c12)
console.log(c13)