ES5的繼承
構(gòu)造函數(shù)的繼承
基本思想:在子類型構(gòu)造函數(shù)的內(nèi)部調(diào)用超類型構(gòu)造函數(shù)炫欺,通過使用apply()和call()方法可以在將來新創(chuàng)建的對(duì)象上執(zhí)行構(gòu)造函數(shù)
// 構(gòu)造函數(shù)
// 構(gòu)造函數(shù)
function Person(name, sex) {
this.name = name;
this.sex = sex;
this.niam= "草擬嗎"
this.run=function(){
console.log(this.name+"在奔跑")
}
}
// 定義Person的原型当凡,原型中的屬性可以被自定義對(duì)象引用
Person.prototype = {
getName: function() {
return this.name;
},
getSex: function() {
return this.sex;
}
}
// Subperson.prototype = new Person()
function Subperson(name, sex, color){
Person.call(this, name, sex)
this.color = color
this.niam= "你阿媽"
this.jump=function(){
console.log(this.name+"---"+this.color+"還活蹦亂跳")
}
}
let sub = new Subperson("小李","男","黑色的");
//console.log(sub.getName()) //這里會(huì)報(bào)錯(cuò) sub.getName is not a function
sub.run()
sub.jump()
$ node es5繼承.js
ZhangSan在奔跑
ZhangSan---黃色的還活蹦亂跳
ChunHua在奔跑
ChunHua---白色的還活蹦亂跳
小李在奔跑
小李---黑色的還活蹦亂跳
繼承父類后蠢正,子類無法使用父類原型上的方法( getName ),只能使用父類構(gòu)造函數(shù)里的方法(run)
通過call或者apply方法稿辙,我們實(shí)際上是在將來新創(chuàng)建的SubType實(shí)例的環(huán)境下調(diào)用了SuperType構(gòu)造函數(shù)昆码。這樣一來,就會(huì)在新SubType對(duì)象上執(zhí)行SuperType函數(shù)中定義的所有對(duì)象初始化代碼邻储,因此未桥,每一個(gè)SubType的實(shí)例都會(huì)有自己的colors對(duì)象的副本
- 優(yōu)點(diǎn)
- 傳遞參數(shù)
- 缺點(diǎn):
方法都在構(gòu)造函數(shù)中定義,函數(shù)無法復(fù)用
在超類型中定義的方法芥备,子類型不可見冬耿,結(jié)果所有類型都只能使用構(gòu)造函數(shù)模式