call 和 apply 方法

1:每个函数都包含两个非继承而来的方法:call(),apply().

2:call方法和apply方法作用是一样的。

下边是call的使用例子:

 1 window.color = 'red';
 2 document.color = 'yellow';
 3 var s1 = {color: 'blue'};
 4 
 5 function getColor (){
 6     console.log(this.color);
 7 }
 8 getColor.call(); //red (默认传递参数)
 9 getColor.call(window);// red
10 getColor.call(document);//yellow
11 getColor.call(s1);//blue
12 getColor.call(this);//red
 1 var Pet={
 2   words : '...',
 3   speak : function(say){console.log(say+ ' ' + this.words);}    
 4 }
 5 
 6 Pet.speak('howling'); //howling...
 7 
 8 
 9 
10 var Dog = {words: 'wang wang'}
11 
12 Pet.speak.call(Dog, 'barking');// barking wang wang

下边是apply使用例子

 1 window.number = 'one';
 2 document.number = 'two';
 3 var s2 = {number: 'three'};
 4 
 5 function getNum(){ console.log(this.number); }
 6 
 7 getNum.apply(); // one 默认
 8 getNum.apply(window); //one
 9 getNum.apply(document);//two
10 getNum.apply(s2);//three
11 getNum.apply(this);//one
 1 function Pet(words){
 2   this.words = words;
 3   this.speak = function(){ console.log(this.words) }  
 4 }
 5 
 6 function Dog(words){
 7    // Pet.call(this, words); 
 8    Pet.apply(this, arguments);
 9 }
10 
11 var dog = new Dog('wang wang');
12 dog.speak();// wang wang

3:不同点是接收参数的方式不同。

function add(c,d){ return this.a + this.b + c + d;}

var s = {a:1, b:2};
console.log( add.call(s,3,4) );// 1+2+3+4 =10
console.log( add.apply(s,[3,4]) ); // 1+2+3+4 =10
 1 window.firstName = "tomF";
 2 window.lastName = "tomL";
 3 var myObj = {firstName:"myF", lastName:"myL"};
 4   
 5 function getName(){ console.log(this.firstName + this.lastName); }
 6   
 7 function getMess(sex, age){ 
 8     console.log(this.firstName + this.lastName+ "性别:"+sex+"age:"+age);
 9 }
10  
11 getName.call(window);//tomFtomL
12 getName.call(myObj);//myFmyL
13 getName.apply(window);//tomFtomL
14 getName.apple(myObj);//myFmyL
15  
16 getMess.call(window,'girl',21);//tomFtomL性别:girlage:21
17 getMess.apply(window,['girl',21]);//tomFtomL性别:girlage:21
18 getMess.call(myObj,'unknown',30);//myFmyL性别:unknownage:30
19 getMess.apply(myObj,['unknown',30]);//myFmyL性别:unknownage:30

猜你喜欢

转载自www.cnblogs.com/ming-os9/p/8945901.html