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

淺談JS繼承_借用構(gòu)造函數(shù) & 組合式繼承

 更新時(shí)間:2016年08月16日 10:00:25   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇淺談JS繼承_借用構(gòu)造函數(shù) & 組合式繼承。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

2.借用構(gòu)造函數(shù)

為解決原型中包含引用類型值所帶來(lái)的問(wèn)題, 我們使用一種叫做 借用構(gòu)造函數(shù)(constructor stealing)的技術(shù)(又叫偽造對(duì)象或經(jīng)典繼承)。

這種技術(shù)的基本思想:在子類構(gòu)造函數(shù)內(nèi)部調(diào)用超類型構(gòu)造函數(shù)。

通過(guò)使用apply()和call()方法可以在新創(chuàng)建的子類對(duì)象上執(zhí)行構(gòu)造函數(shù)。

function SuperType(){
  this.colors = ["red", "blue", "green"];
}

function SubType(){
  //繼承了 SuperType
  SuperType.apply(this);
}

var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors);  //red,blue,green,black

var instance2 = new SubType();
alert(instance2.colors);  //red,blue,green

在上述例子中,實(shí)際上是在新創(chuàng)建的SubType實(shí)例(instance1 instance2)的環(huán)境下調(diào)用了SuperType的構(gòu)造函數(shù)。這樣一來(lái),就會(huì)在新SubType對(duì)象上執(zhí)行SuperType()函數(shù)中定義的所有對(duì)象初始化代碼。 所以Subtype的每個(gè)實(shí)例就都會(huì)具有自己的colors屬性的副本了。

傳遞參數(shù)

對(duì)于原型鏈來(lái)講,借用構(gòu)造函數(shù)有一個(gè)很大的優(yōu)勢(shì),即可以在子類型構(gòu)造函數(shù)中想超類型構(gòu)造函數(shù)傳遞參數(shù)。

function SuperType(name){
  this.name = name;
}

function SubType(){
  SuperType.call(this, "Bob");
  this.age = 18;
}

var instance1 = new SubType();
alert(instance1.age);  //18
alert(instance1.name);  //Bob

借用構(gòu)造函數(shù)的問(wèn)題:

方法都在構(gòu)造函數(shù)中定義,因此函數(shù)復(fù)用就無(wú)從談起了。而且,在超類型的原型中定義的方法,對(duì)子類型而言也是不可見(jiàn)的。

3. 組合繼承

組合繼承(combination inheritance), 有時(shí)候也叫作偽經(jīng)典繼承, 指的是將原型鏈和借用構(gòu)造函數(shù)的技術(shù)組合到一起。從而發(fā)揮二者之長(zhǎng)的一種繼承模式。

使用原型鏈實(shí)現(xiàn)對(duì)原型屬性和方法的繼承;

通過(guò)借用構(gòu)造函數(shù)來(lái)實(shí)現(xiàn)對(duì)實(shí)例屬性的繼承。

這樣,既通過(guò)在原型上定義方法實(shí)現(xiàn)了函數(shù)的復(fù)用,又能保證每個(gè)實(shí)例都有他自己的屬性。

function SuperType(name){
  this.name = name;
  this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
  alert(this.name);
}

function SubType(name, age){
    //繼承屬性
  SuperType.call(this, name);
  this.age = age;
}

  //繼承方法
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function(){
  alert(this.age);
}

var instance1 = new SubType("Bob", 22);
instance1.colors.push("black");
alert(instance1.colors);   //red,blue,green,black
instance1.sayName();     //Bob
instance1.sayAge();     //22

var instance2 = new SubType("Alice", 21);
alert(instance2.colors);  //red,blue,green
instance2.sayName();    //Alice
instance2.sayAge();     //21

在這個(gè)例子中, SuperType構(gòu)造函數(shù)定義了兩個(gè)屬性: name和colors。 SuperType的原型定義了一個(gè)方法sayName()。

SubType構(gòu)造函數(shù)在調(diào)用SuperType構(gòu)造函數(shù)時(shí)傳入了name參數(shù),定義了他自己的屬性age。然后將SuperType的實(shí)例賦值給SubType的原型。在該原型上定義了方法sayAge()。

這樣一來(lái),就可以讓兩個(gè)不同的SubType實(shí)例既分別擁有自己的屬性 - 包括colors屬性,又可以使用相同的方法。

以上這篇淺談JS繼承_借用構(gòu)造函數(shù) & 組合式繼承就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論