1. 程式人生 > >【Infragistics教程】在javascript建構函式中建立基本繼承

【Infragistics教程】在javascript建構函式中建立基本繼承

【下載Infragistics Ultimate最新版本】

用javascript建立物件有四種方法。具體如下:

  1. 物件作為文字
  2. 建構函式呼叫模式
  3. 建立()方法
  4. 在ES6之後使用類

繼承的實現因物件建立方法而異。本文將解釋如何在函式建構函式之間建立繼承。

假設您有一個函式:

1

2

3

4

function animal(name, age) {

    this.name = name;

    this.age = age;

}

如果使用new操作符呼叫animal函式,將建立一個物件。這種物件建立方式也稱為“建構函式呼叫模式”。

1

2

3

4

var dog = new animal('foo', 5);

console.log(dog);

var cat = new animal('koo', 3);

console.log(cat);

物件dog和cat都有自己的名稱和年齡屬性。如果希望在所有物件之間共享屬性或方法,請將其新增到函式原型中。

1

2

3

4

animal.prototype.canRun = 

function () {

  

    console.log('yes ' this.name + ' can run !');

}

使用javascript原型鏈,dog和cat物件都可以訪問canrun方法。

1

2

3

4

5

var dog = new animal('foo', 5);

dog.canRun(); // yes foo can run

 

var cat = new animal(

'koo', 3);

cat.canRun(); // yes koo can run

接下來,讓我們建立另一個建構函式——人:

1

2

3

4

5

6

7

8

function human(name, age, money) {

    this.name = name ;

    this.age = age ;

    this.money = money;

}

human.prototype.canEarn = function () {

    console.log('yes ' this.name + 'can earn');

}

此時,人與動物的功能沒有任何關係。然而,我們知道人也是動物。人工構造有兩個問題。

  1. 它有重複的名稱和年齡初始化程式碼。為此,應使用動物建造師。
  2. 它與動物建造師沒有任何聯絡

上述兩個問題可以通過在動物和人類功能構建者之間建立繼承來消除。

您可以通過如下修改人工函式來解決程式碼複製的問題1:

1

2

3

4

function human(name, age, money) {

    animal.call(this, name, age);

    this.money = money;

}

現在,在人類函式中,我們使用call方法手動傳遞當前物件作為動物函式中“this”的值。這種方法也稱為間接呼叫模式。現在,可以建立一個人類物件例項,如下所示:

1

2

var h1 = new human('dj', 30, '2000 $');

console.log(h1);

到目前為止,我們已經解決了程式碼複製的第一個問題,但是人類的功能仍然與動物的功能無關。如果您嘗試對h1物件呼叫canrun方法,javascript將向您丟擲一個錯誤。

1

h1.canRun(); // throw error canRun is not a function

您可以通過將人類功能原型與動物功能建構函式原型連結來解決這個問題。有兩種方法可以做到這一點。

使用γ原型

使用object.create()方法

您可以使用object.create()連結函式建構函式的原型,如下所示:

1

human.prototype = Object.create(animal.prototype);

您可以使用_uu proto_uuu連結函式建構函式的原型,如下所示:

1

human.prototype.__proto__ = animal.prototype;

更推薦object.create()方法,因為在許多瀏覽器中可能不支援_uuProto。在連結原型之後,在一種方式下,您已經在動物和人類函式建構函式之間建立了繼承。人的物件例項可以讀取動物功能的所有屬性,並且可以執行動物功能方法。

下面列出了實現函式建構函式之間繼承的完整原始碼,供您參考:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

function animal(name, age) {

  

    this.name = name;

    this.age = age;

  

}

  

animal.prototype.canRun = function () {

  

    console.log('yes ' this.name + ' can run !');

}

  

var dog = new animal('foo', 5);

dog.canRun();

  

var cat = new animal('koo', 3);

cat.canRun();

function human(name, age, money) {

    animal.call(this, name, age);

    this.money = money;

}

  

human.prototype = Object.create(animal.prototype);

  

human.prototype.canEarn = function () {

    console.log('yes ' this.name + 'can earn');

}

// human.prototype.__proto__ = animal.prototype;

var h1 = new human('dj', 30, '2000 $');

h1.canRun();

h1.canEarn();

要在函式建構函式之間建立繼承,請始終執行以下兩個操作:

  1. 使用call或apply呼叫父建構函式。
  2. 將子建構函式原型連結到父建構函式原型