JavaScript中call和apply方法的使用

acvaScript中的call()方法和apply()方法,在某些時候這兩個方法還確實是十分重要的。
1. 每一個函數都包含兩個非繼承而來的方法:call()方法和apply()方法。
2. 相同點:這兩個方法的做用是同樣的。
都是在特定的做用域中調用函數,等於設置函數體內this對象的值,以擴充函數賴以運行的做用域。
通常來講,this老是指向調用某個方法的對象,可是使用call()和apply()方法時,就會改變this的指向。

call()方法使用示例:數組

 1 //例一
 2   window.color = 'red';
 3   document.color = 'yellow';
 4   var s1 = { color: 'blue' };
 5   function changeColor() {
 6     console.log(this.color);
 7   }
 8   changeColor.call(); //red (默認傳遞參數) 
 9   changeColor.call(window); //red
10   changeColor.call(document); //yellow 
11   changeColor.call(this); //red 
12   changeColor.call(s1); //blue
 1 //例二
 2  var Pet = {
 3     words : '...', 
 4     speak : function (say) {
 5        console.log(say + ''+ this.words) 
 6        } 
 7   }
 8   Pet.speak('Speak'); // 結果:Speak... 
 9   var Dog = { words:'Wang' } //將this的指向改變成了Dog 
10   Pet.speak.call(Dog, 'Speak'); //結果: SpeakWang

apply()方法使用示例:app

 

 1 //例一
 2  window.number = 'one';
 3  document.number = 'two'; 
 4  var s1 = {number: 'three' }; 
 5  function changeColor(){ 
 6    console.log(this.number); 
 7  } changeColor.apply(); //one (默認傳參) 
 8  changeColor.apply(window); //one 
 9  changeColor.apply(document); //two 
10  changeColor.apply(this); //one
11  changeColor.apply(s1); //three

 

 1  //例2 
 2  function Pet(words){ 
 3    this.words = words; 
 4    this.speak = function () { 
 5       console.log( this.words) 
 6    } 
 7 } 
 8 function Dog(words){ 
 9    //Pet.call(this, words); //結果: Wang 
10    Pet.apply(this, arguments); //結果: Wang 
11 } 
12 var dog = new Dog('Wang');
13  dog.speak();

3. 不一樣點:接收參數的方式不一樣。
1.apply()方法 接收兩個參數,一個是函數運行的做用域(this),另外一個是參數數組。

語法:apply([thisObj [,argArray] ]);,調用一個對象的一個方法,另外一個對象替換當前對象。

說明:若是argArray不是一個有效數組或不是arguments對象,那麼將致使一個
TypeError,若是沒有提供argArray和thisObj任何一個參數,那麼Global對象將用做thisObj。

2.call()方法 第一個參數和apply()方法的同樣,可是傳遞給函數的參數必須列舉出來。

語法:call([thisObject[,arg1 [,arg2 [,...,argn]]]]);,應用某一對象的一個方法,用另外一個對象替換當前對象。

說明: call方法能夠用來代替另外一個對象調用一個方法,call方法能夠將一個函數的對象上下文從初始的上下文改變爲thisObj指定的新對象,若是沒有提供thisObj參數,那麼Global對象被用於thisObj。函數

1 //例一
2 function add(c,d){ 
3    return this.a + this.b + c + d; 
4 } 
5 var s = {a:1, b:2}; 
6 console.log(add.call(s,3,4)); // 1+2+3+4 = 10 
7 console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14 
 1 //例二
 2  window.firstName = "Cynthia";
 3  window.lastName = "_xie"; 
 4  var myObject = {firstName:'my', lastName:'Object'}; 
 5  function getName(){ 
 6     console.log(this.firstName + this.lastName); 
 7 } 
 8 function getMessage(sex,age){
 9     console.log(this.firstName + this.lastName + " 性別: " + sex + " age: " + age ); 
10 } 
11 getName.call(window); // Cynthia_xie 
12 getName.call(myObject); // myObject 
13 getName.apply(window); // Cynthia_xie 
14 getName.apply(myObject);// myObject 
15 getMessage.call(window,"女",21); //Cynthia_xie 性別: 女 age: 21 
16 getMessage.apply(window,["女",21]); // Cynthia_xie 性別: 女 age: 21 
17 getMessage.call(myObject,"未知",22); //myObject 性別: 未知 age: 22 
18 getMessage.apply(myObject,["未知",22]); // myObject 性別: 未知 age: 22

在實際開發中,常常會遇到this指向被不經意改變的場景。
有一個局部的fun方法,fun被做爲普通函數調用時,fun內部的this指向了window,但咱們每每是想讓它指向該#test節點,見以下代碼:this

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   console.log(this.id);//test
4   var fun = function(){
5     console.log(this.id);
6   }
7   fun();//window
8 }

使用call,apply咱們就能夠輕鬆的解決這種問題了spa

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   console.log(this.id);//test
4   var fun = function(){
5     console.log(this.id);
6   }
7   fun.call(this);//test
8 }

還能夠有這樣的方法:prototype

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   var that = this;
4   console.log(this.id);//test
5   var fun = function(){
6     console.log(that.id);
7   }
8   fun();//test
9 }

不過在ES5的嚴格模式下,this的指向不被規定爲全局對象,而是undefined。code

1 function func(){
2   "use strict"
3   alert ( this );  // 輸出:undefined
4 }
5 func();

call和apply方法還有其餘用法
對象

類數組blog

這裏把符合如下條件的對象稱爲類數組
繼承

1.具備length屬性

2.按索引方式存儲數據

3.不具備數組的push,pop等方法

常見類數組有 arguments,NodeList!

1 (function(){
2   Array.prototype.push.call(arguments,4);
3   console.log(arguments);//[1, 2, 3, 4]
4 })(1,2,3)

這樣就往arguments中push一個4進去了

Array.prototype.push 頁能夠實現兩個數組合並

一樣push方法沒有提供push一個數組,可是它提供了push(param1,param,…paramN) 因此一樣也能夠經過apply來裝換一下這個數組,即:

 

 

1 var arr1=new Array("1","2","3"); 
2 var arr2=new Array("4","5","6"); 
3 Array.prototype.push.apply(arr1,arr2); 
4 console.log(arr1);//["1", "2", "3", "4", "5", "6"]

 

也能夠這樣理解,arr1調用了push方法,參數是經過apply將數組裝換爲參數列表的集合.

再好比我想求類數組中的最大值

1 (function(){
2   var maxNum = Math.max.apply(null,arguments);
3   console.log(maxNum);//56
4 })(34,2,56);

還能夠判斷數據類型:

 

1 console.log(Object.prototype.toString.call(123)) //[object Number]
2 console.log(Object.prototype.toString.call('123')) //[object String]
3 console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
4 console.log(Object.prototype.toString.call(true)) //[object Boolean]
5 console.log(Object.prototype.toString.call({})) //[object Object]
6 console.log(Object.prototype.toString.call([])) //[object Array]
7 console.log(Object.prototype.toString.call(function(){})) //[object Function]
相關文章
相關標籤/搜索