js继承的几种方法

1.原型链继承:子类对象指向父类的实例以实现继承

 1 function Parent()
 2 {
 3     this.sayAge = function()
 4     {
 5         console.log(this.age)
 6     }
 7 };
 8 function Child(firstname)
 9 {
10     this.firstname = firstname;
11     this.age = 10;
12     this.say = function()
13     {
14         this.sayAge();//继承父类sayAge
15         console.log(this.firstname)
16     }
17 }
18 Child.prototype = new Parent();//子类对象指向父类实例
19 var people = new Child("张三");   //实例化子类时参数不能传递给父类
20 people.say();

2.call继承   类似于apply继承

 1 function Parent(firstname)
 2 {
 3     this.firstname = firstname;
 4     this.age = 40;
 5     this.sayAge = function()
 6     {
 7         console.log(this.age);
 8     }
 9 }
10 function Child()
11 {
12 
13     this.say = function()
14     {
15         console.log(this.firstname);
16         this.sayAge();
17     }
18 
19 }
20 var child = new Child();
21 Parent.call(child,'张三');
22 child.say();

3.混合模式实现继承(原型链和call)

 1 function Parent()
 2 {
 3 
 4     this.sayAge=function()
 5     {
 6         console.log(this.age);
 7     }
 8 }
 9 
10 Parent.prototype.sayParent=function()
11 {
12    console.log("this is parentmethod!!!");
13 }
14 
15 function Child(firstname)
16 {
17     Parent.call(this);
18     this.firstname=firstname;
19     this.age=40;
20     this.saySomeThing=function()
21     {
22         console.log(this.firstname);
23         this.sayAge();
24     }
25 }
26 
27 Child.prototype=new  Parent();
28 var child=new Child("张");
29 child.saySomeThing();
30 child.sayParent();

 

call解析

 1     var func=new function()
 2     {
 3         this.a="func"
 4     }; 
 5     var myfunc=function(x)
 6     {  
 7         var a="myfunc";  
 8         alert(this.a);  
 9         alert(x);  
10     }  
11     myfunc.call(func,"var");//myfunc 父类   func子类(当前对象)func继承父类的方法  ‘var’传递给父类的参数

 

posted @ 2015-05-06 17:18  张彦正  阅读(141)  评论(0编辑  收藏  举报