call、apply 个人理解

 1 /**
 2  **  call 及 apply  应用  
 3      call(thisObj,pam1,pam2...)      thisObj 表示当前对象实例及代入this作用域,参数为单个传入方式
 4      apply(thisObj,[a1,a2])          thisObj 表示当前对象实例及代入this作用域,参数为数组方式传入
 5 **/
 6 
 7 var Animal = function(name)
 8 {
 9     this.name = name;
10     this.sayHi = function()
11     {
12         console.log('myNameis: ' + this.name + '\n');
13 
14         //这里返回传入对象实现 责任链的方式
15         return this; 
16     }
17 }
18 
19 var Cat = function(name)
20 {
21     Animal.call(this,name);
22 
23     //这里没有重写sayHi,没用还是引用Animal的 return this;
24     this.wo = function(){
25 
26         console.log(this.name + ' 我再次被调用了......\n');
27     }
28 }
29 
30 
31 var Dog = function(name)
32 {
33     Animal.apply(this,name);
34 
35     //这里的方法想当于是重写覆盖调用对象Animal中的sayHi方法
36     this.sayHi = function(){
37 
38         console.log(this.name + ' 咬人...\n');
39 
40         //下面调用的wo方法必须 return this
41         return this;
42     };
43 
44     this.wo = function(){
45 
46         console.log(this.name + ' 我再次被调用了......\n');
47     }
48 } 
49 
50 new Cat('喵喵叫...').sayHi().wo();
51 new Dog(['汪汪叫...']).sayHi().wo();

 

posted @ 2016-11-22 11:35  Mr.Tom  阅读(96)  评论(0)    收藏  举报