JavaScript中的继承

在JavaScript中没有Java中的exends关键字,只能通过其他的方式来实现继承关系。

1) 对象冒充

 1 function Parent(username)
 2 {
 3     this.username = username;
 4 
 5     this.sayHello = function()
 6     {
 7         alert(this.username);
 8     }
 9 }
10 
11 function Child(username, password)
12 {
13     //下面三行代码是就是实现了Child继承Parent的关键代码
14     this.method = Parent;
15     this.method(username);
16     delete this.method;
17 
18     this.password = password;
19 
20     this.sayWorld = function()
21     {
22         alert(this.password);
23     }
24 }
25 
26 var parent = new Parent("zhangsan");
27 var child = new Child("lisi", "1234");
28 parent.sayHello();
29 child.sayHello();
30 child.sayWorld();

2) call方法方式。
call方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第2个参数开始,逐一赋值给函数中的参数。

 1 //使用call方式实现对象的继承
 2 
 3 function Parent(username)
 4 {
 5     this.username = username;
 6 
 7     this.sayHello = function()
 8     {
 9         alert(this.username);
10     }
11 }
12 
13 function Child(username, password)
14 {
15         //下面的一行代码是第一种方式三行关键代码的替换
16     Parent.call(this, username);
17 
18     this.password = password;
19 
20     this.sayWorld = function()
21     {
22         alert(this.password);
23     }
24 }
25 
26 var parent = new Parent("zhangsan");
27 
28 var child = new Child("lisi", "123");
29 
30 parent.sayHello();
31 
32 child.sayHello();
33 child.sayWorld();        

3) apply方法方式

 1 //使用apply方法实现对象继承
 2 function Parent(username)
 3 {
 4     this.username = username;
 5 
 6     this.sayHello = function()
 7     {
 8         alert(this.username);
 9     }
10 }
11 
12 function Child(username, password)
13 {
14     Parent.apply(this, new Array(username));
15 
16     this.password = password;
17 
18     this.sayWorld = function()
19     {
20         alert(this.password);
21     }
22 }
23 
24 var parent = new Parent("zhangsan");
25 var child = new Child("lisi", "123");
26 
27 parent.sayHello();
28 
29 child.sayHello();
30 child.sayWorld();

4)原型链方式(无法给构造函数传参数)

 1 function Parent()
 2 {
 3 
 4 }
 5 
 6 Parent.prototype.hello = "hello";
 7 Parent.prototype.sayHello = function()
 8 {
 9     alert(this.hello);
10 }
11 
12 function Child()
13 {
14 
15 }
16 
17 Child.prototype = new Parent();
18 
19 Child.prototype.world = "world";
20 Child.prototype.sayWorld = function()
21 {
22     alert(this.world);
23 }
24 
25 var child = new Child();
26 
27 child.sayHello();
28 child.sayWorld();

5)混合方式(推荐)

 1 function Parent(hello)
 2 {
 3     this.hello = hello;
 4 }
 5 
 6 Parent.prototype.sayHello = function()
 7 {
 8     alert(this.hello);
 9 }
10 
11 function Child(hello, world)
12 {
13     Parent.call(this, hello);
14 
15     this.world = world;
16 }
17 
18 Child.prototype = new Parent();
19 
20 Child.prototype.sayWorld = function()
21 {
22     alert(this.world);
23 }
24 
25 var child = new Child("hello", "world");
26 
27 child.sayHello();
28 child.sayWorld();
原文地址:https://www.cnblogs.com/daneres/p/4787543.html