JS 寄生式组合继承
大约 1 分钟
JS
寄生式组合继承
1.原型链继承(使用Call | Bind | apply)
// 通过call 方法传递参数
function Father() {
console.log("进入父亲的方法i")
this.myFather = "父亲"
}
Father.prototype.eat = function () {
console.log(this)
console.log(`${this.name}和${this.myFather}一起玩耍}`)
}
function Son(name, age) {
this.name = name;
this.age = age
Father.call(this)
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
let SonObj = new Son("儿子", 15);
SonObj.eat();
2.寄生式组合继承(就是搞个中间类)
// 寄生式组合继承 利用中间类来搞
function Father() {
console.log("进入父亲的方法i")
this.myFather = "父亲"
}
Father.prototype.eat = function () {
console.log(this)
console.log(`${this.name}和${this.myFather}一起玩耍}`)
}
function Son(name, age) {
this.name = name;
this.age = age
Father.call(this)
}
function Middle() {
}
Middle.prototype = Father.prototype;
Son.prototype = new Middle();
Son.prototype.constructor = Son;
let SonObj = new Son("儿子", 15);
SonObj.eat();
2.1 优化版本
// 优化终极版本寄生式组合继承 利用中间类来搞
function Father() {
console.log("进入父亲的方法i")
this.myFather = "父亲"
}
Father.prototype.eat = function () {
console.log(this)
console.log(`${this.name}和${this.myFather}一起玩耍}`)
}
function Son(name, age) {
this.name = name;
this.age = age
Father.call(this)
}
function _extends(parent, son) {
function Middle() {
this.constructor = son
this.count = 23
}
Middle.prototype = parent.prototype;
return new Middle()
}
Son.prototype = _extends(Father, Son)
let SonObj = new Son("儿子", 15);
let SonObj2 = new Son("儿子2", 15);
SonObj.eat();
SonObj2.eat();
Object.create
来完成寄生组合继承
3.利用
function Father() {
console.log("进入父亲的方法i")
this.myFather = "父亲"
}
Father.prototype.eat = function () {
console.log(this)
console.log(`${this.name}和${this.myFather}一起玩耍}`)
}
function Son(name, age) {
this.name = name;
this.age = age
Father.call(this)
}
Son.prototype = Object.create(Father.prototype, {
count: {
writable: true,
value: 23
}
})
Son.prototype.constructor = Son
let SonObj = new Son("儿子", 15);
let SonObj2 = new Son("儿子2", 15);
console.log(SonObj2);
SonObj.eat();
SonObj2.eat();