call 和 apply 方法

1:每一個函數都包含兩個非繼承而來的方法:call(),apply().app

2:call方法和apply方法做用是同樣的。函數

下邊是call的使用例子:this

 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使用例子spa

 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:不一樣點是接收參數的方式不一樣。code

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
相關文章
相關標籤/搜索