欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談Javascript實現(xiàn)繼承的方法

 更新時間:2015年07月06日 09:22:26   投稿:hebedich  
本文給大家簡單介紹了下如何在javascript中實現(xiàn)繼承的幾種方法,十分的實用,有需要的小伙伴可以參考下。

S1:js中一切皆對象,想想如果要實現(xiàn)對父對象屬性和方法的繼承,最初我們會怎樣子來實現(xiàn)呢,考慮到原型的概念,最初我是這樣來實現(xiàn)繼承的

function Parent(){
   this.name='123';
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
console.log('Name :'+son.getName()+';Age: '+son.getAge());
 
 
VM1777:16 Name :123;Age: 20

從上面可以看到實現(xiàn)對Parent的繼承主要是覆寫了Son的prototype,這樣便把Parent的屬性和方法過給了Son的原型,這樣子在通過new Son()構造出來的對象均會繼承來自原型【即父對象Parent】的屬性和方法,這樣就達到了繼承效果;但這樣會帶來一個副作用,就是當父對象中包含引用類型的屬性時,子對象對引用類型數(shù)據(jù)的修改,會影響到所有的子對象,顯然這不是我們需要的效果:

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push('pear');
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple", "pear"]

S2:目前想到要解決這個問題就是使每個子對象都擁有一份父對象屬性的復制品,這樣修改屬性時只是修改了子對象下的屬性,而不會影響到其他的子對象屬性。這一目標的實現(xiàn)參照前人的對象冒充的方式來實現(xiàn)

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
Son.prototype=new Parent();
Son.prototype.getAge=function(){
   return this.age;
}
var son=new Son();
var son1=new Son();
console.log(son.fruits);//["apple"]
console.log(son1.fruits);//["apple"]
son.fruits.push('pear');
console.log(son.fruits);//["apple", "pear"]
console.log(son1.fruits);//["apple"]

上面我在Son函數(shù)里加了Parent.call(this)實現(xiàn)在new Son()的時候?qū)his[即new 出來的Son對象]冒充成Parent函數(shù)里的上下文this來調(diào)用Parent()函數(shù),從而拿到了父對象的屬性和方法副本,所以在接下來修改父對象的屬性和方法時其實是修改的副本,故達到了不會影響全部子對象的效果。但是由于Son.prototype=new Parent()的使用,我們得到了兩份實例的屬性和方法,而再我們拿到了副本以后,只是需要父對象的原型就行了,從下面可以看出我們只需要原型中的getname();

S3:接下來就是要去掉一份實例的屬性和方法,這時候是constructor發(fā)揮作用的時候了,看下邊代碼,將Parent.prototype重新構建成一個原生對象,來作為子對象的原型,再把constructor指向子構造器

function Parent(){
   this.name='123';
   this.fruits=['apple'];
}
Parent.prototype.getName=function(){
   return this.name;
}
function Son(){
   Parent.call(this);
   this.age=20;
}
function Extend(Parent,Son){
   var proto = new Object(Parent.prototype);
   proto.constructor = Son;
   Son.prototype=proto;
}
Extend(Parent,Son);
Son.prototype.getAge=function(){
   return this.age;
}

以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。

相關文章

最新評論