ES6之前,JavaScript并沒有繼承這一現(xiàn)有的機制。
ES5的繼承方式
類式繼承
//聲明父類function Father(){this.fatherVal = 'father';}//為父類添加共有方法Father.prototype.getFatherValue = function(){return this.fatherVal;}//聲明子類 function Child(){this.childVal = 'child';}//繼承父類Child.prototype = new Father();//為子類添加共有方法Child.prototype.getChildValue = function(){return this.childVal;}子類的prototype被賦予父類的實例,新創(chuàng)建的對象復制了父類的構造函數(shù)內的屬性和方法并且將原型_proto_指向了父類的原型對象,這樣就擁有了父類的原型對象上的屬性和方法與父類構造函數(shù)中復制的屬性和方法。
var instance = new Child();console.log(instance.getFatherValue()); //fatherconsole.log(instance.getChildValue()); //childconsole.log(instance instanceof Child); //trueconsole.log(instance instanceof Father); //trueconsole.log(instance instanceof Object); //trueconsole.log(Child instanceof Father); //falseconsole.log(Child.prototype instanceof Father); //true
缺點:
1.子類實例共用父類的公有引用屬性。
2.無法對父類構造函數(shù)內的屬性進行傳參初始化。
function Father(){this.companies =['bigo','yy','uc']}funtion Child(){}Child.prototype = new Father();var instanceA = new Child();var instanceB = new Child();console.log(instanceB.companies); //['bigo','yy','uc']instanceA.companies.push('nemo');console.log(instanceB.companies); //['bigo','yy','uc','nemo']構造函數(shù)繼承
//聲明父類function Father(val){this.companies =['bigo','yy','uc']this.val = val;}//聲明父類原型方法Father.prototype.getCom = function(){console.log(this.companies);}//聲明子類function Child(val){//繼承Father.call(this,val);}var instanceA = new Child('childA');var instanceB = new Child('childB');instanceA.companies.push('nemo');console.log(instanceA.companies); //['bigo','yy','uc','nemo']console.log(instanceA.val); //childAconsole.log(instanceB.companies); //['bigo','yy','uc']console.log(instanceB.val); //childB對Child調用call,將子類中的變量在父類中執(zhí)行一遍,然后父類給this綁定,所以子類繼承了父類的公有屬性。
缺點:
由于這種類型的繼承沒有設計原型prototype,所以父類的原型方法不會被子類繼承,而如果想被子類繼承就必須放在構造函數(shù)中,這樣創(chuàng)建出來的每個實例都會單獨擁有一份而不能共用。
組合繼承
//聲明父類function Father(val){this.companies =['bigo','yy','uc']this.val = val;}//聲明父類原型方法Father.prototype.getValue = function(){console.log(this.val);}//聲明子類function Child(val,newVal){//構造函數(shù)式繼承Father.call(this,val);this.newVal = newVal;}//類式繼承Child.prototype = new Father();//聲明子類原型方法Child.prototype.getNewValue = function(){console.log(this.newVal);}var instanceA = new Child("fatherA","childA");instanceA.companies.push('nemo');console.log(instanceA.companies); //['bigo','yy','uc','nemo']instanceA.getValue(); //fatherAinstanceA.getNewValue(); //childAvar instanceB = new Child("fatherB","childB");console.log(instanceA.companies); //['bigo','yy','uc']instanceB.getValue(); //fatherBinstanceB.getNewValue(); //childB
新聞熱點
疑難解答
圖片精選