【Infragistics教程】在javascript构造函数中建立基本继承

【下载Infragistics Ultimate最新版本】javascript

用javascript建立对象有四种方法。具体以下:java

  1. 对象做为文本
  2. 构造函数调用模式
  3. 建立()方法
  4. 在ES6以后使用类

继承的实现因对象建立方法而异。本文将解释如何在函数构造函数之间建立继承。浏览器

假设您有一个函数:app

1函数

2this

3spa

4prototype

function animal(name, age) {code

    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. 将子构造函数原型连接到父构造函数原型
相关文章
相关标签/搜索