知識(shí)點(diǎn):
-
通過原型鏈來實(shí)現(xiàn)子類和父類的關(guān)聯(lián),通過instanceof 來檢測(cè)兩者之間關(guān)系。
obj instanceof constructor //可以檢測(cè)objd的constructor.prototype是否在obj的原型鏈上
構(gòu)造函數(shù)(prototype)和實(shí)例對(duì)象(__proto__)都指向構(gòu)造函數(shù)的原型對(duì)象
原型對(duì)象中constructor指向構(gòu)造函數(shù)。
核心:
若使子類的實(shí)例原型鏈上有父類的prototype,可以將子類的prototype設(shè)置為父類的實(shí)例(更好的是設(shè)為父類prototype的副本)
function Super(name){
this.name=name;
}
Super.prototype.say=function(){
alert('g');
}
function Sub(name,age){
Super.call(this,name);
this.age=age;
}
inherit(Sub,Super);
Sub.prototype.talk=function(){
alert('g');
}
function inherit(sub,sup){
var prototype=Object.create(sup.prototype);
prototype.constructor=sub;
sub.prototype=prototype
}