方法call()、apply()、bind()都保存在函數的prototype名下(所以每一個函數均可以直接調用)。都用於改變函數的執行環境。數組
call()和apply()實際功能一致。
call()和apply()在原函數擁有參數的時候,不能只有一個參數了。app
function add(num1,num2){ console.log(num1+num2); } function show(num1,num2){ return add.call(null,num1,2); } show(2,3); //輸出結果爲4 function add(num1,num2){ console.log(num1+num2); } function show(num1,num2){ return add.call(null,num1); } show(2,3); //輸出結果爲NAN
在非嚴格模式下,call(null) 等價於 call(this) 和 call(undefined)
call()必須把函數參數寫全,不然沒法正確運行。
apply()能夠理解爲,第二個參數若是須要,必須傳入所有參數組成的一個數組,或者arguments。函數
call()和apply()是直接調用,而bind()的做用:建立一個函數的實例,執行環境變爲bind的參數。對的,只是建立一個函數實例,所以通常須要以值的形式傳遞之。this
var cat = {color:"blue"}; window.color = "red"; function showColor(){ console.log(this.color); } showColor.bind(cat); //沒有任何輸出 showColor.bind(cat)(); //輸出blue var newShowColor = showColor.bind(cat); newShowColor(); //輸出blue
bind()可用於setTimeout()、setInterval()或者事件處理(document),被綁定的函數也會用掉更多的內存。prototype
function bind(fn,arg){ return function(){ return fn.apply(arg,arguments); } }
這裏的arg是執行環境對象,arguments是fn函數自己的參數。
bind(showColor,cat);等價於showColor.bind(cat);code