apply語法
func.apply(name, [array])
- 第一個參數指定函數體內this對象的指向.
- 第二個參數為一個帶下標的集合,可以是數組或類數組,apply方法把這個集合中的元素作為參數傳遞給被調用的函數
var func = function(a, b, c) {console.log([a, b, c]); // [1,2,3]
}
func.apply(null, [1,2,3])
call語法
- 第一個參數:代表函數體內this指向
- 第二個參數:數量不固定,每個參數依次傳入函數 ```javascript
```
當使用call或則apply的時候, 如果我們傳入的第一個參數是null. 函數體內的this會指向默認的宿主對象,在游覽器中則是window
var func = function( a, b, c ){alert ( this === window ); // 輸出true
};
func.apply( null, [ 1, 2, 3 ] );
但如果是在嚴格模式下,函數體內的this還是為null:
var func = function( a, b, c ){ "use strict"; alert ( this === null ); // 輸出true
}
func.apply( null, [ 1, 2, 3 ] );
有時候我們使用call或者apply的目的不在于指定this指向,而是另有用途,比如借用其他對象的方法。
那么我們可以傳入null來代替某個具體的對象:
Math.max.apply( null, [ 1, 2, 5, 3, 4 ] ) // 輸出:5
call和apply的用途
var obj1={name: '李小龍'
}
var obj2={name: '蕭薰'
}
window.name = 'window'
var getName = function(){console.log(this.name)
};
getName(); //輸出:window
getName.call(obj1); //輸出:李小龍
getName.call(obj2); //輸出:蕭薰
當執行getName.call( obj1 )這句代碼時,getName函數體內的this就指向obj1對象
this 錯誤的情況
document.getElementById( 'div1' ).onclick = function(){
alert( this.id ); // 輸出:div1
var func = function(){ alert ( this.id ); // 輸出:undefined
}
func();
};
修正this
document.getElementById( 'div1' ).onclick = function(){
var func = function(){ alert ( this.id ); // 輸出:div1
}
func.call( this );
};
原文鏈接: http://www.jianshu.com/p/c942d58659c6