1.call方法作用:
讓原型上的 call 方法執(zhí)行,在執(zhí)行 call 方法時(shí),讓調(diào)用 call 的方法中的 this 指向 call 方法里的第一個(gè)參數(shù),再執(zhí)行調(diào)用 call 的這個(gè)方法。
var obj = {name:'Jula'}
function fn(){
var name = 'Locy';
console.log(this.name);
}
fn.call(obj)
function fn1(){console.log(1)}
function fn2(){console.log(2)}
fn1.call(fn2); //1 最終執(zhí)行 fn1
fn1.call.call(fn2) // 2 最終執(zhí)行 fn2
Function.prototype.call(fn1) // undefined 執(zhí)行Function.prototype 是匿名(空)函數(shù)
Function.prototype.call.call.call(fn1) //1 最終執(zhí)行 fn1
首先 fn1 通過(guò)原型鏈機(jī)制找到 Function.prototype 找到 call 方法,并且讓 call 方法執(zhí)行,此時(shí) call 這個(gè)方法中的 this 就是要操作的 fn1,在 call 方法執(zhí)行過(guò)程中讓 fn1 的 “this 關(guān)鍵字” 變?yōu)?fn2,然后再執(zhí)行 fn1,fn1 的執(zhí)行結(jié)果為 1。
fn1.call.call(fn2) 最后一個(gè) call 方法執(zhí)行,fn1.call -> 執(zhí)行時(shí),讓里面的 this 變?yōu)?fn2 ,所以 fn1.call 即為 fn2 執(zhí)行。
2. 非嚴(yán)格模式和嚴(yán)格模式下的 call 的行為:
function fn(num1,num2){
console.log(num1 + num2);
console.log(this);
}
fn(100,200) // 分別輸出 : 300 window
fn.call(100,300) // 分別輸出 :NaN Number 讓 this 指向第一個(gè)參數(shù),以后的參數(shù)給 fn 傳值。
fn.call() // this-> window , 在嚴(yán)格模式下 this -> undefined
fn.call(null) // this -> window ,在嚴(yán)格模式下 this -> null
fn.call(undefined) // this -> window ,在嚴(yán)格模式下 this -> undefined
3. call、apply 、bind 區(qū)別:
apply 方法傳遞參數(shù)時(shí),必須把參數(shù)放在一個(gè)數(shù)組中傳值。
bind :
var obj ={name: 'jack'}
function fn(a,b){
console.log(a+b,this);
}
fn.call(obj,1,3) // 4, obj
var re = fn.bind(obj, 1, 3)
re() // 4 , obj
bind 方法在 IE6 ~8 下不兼容,bind 只是改變了 fn 中的 this 改變?yōu)?obj ,并向 fn 里傳遞參數(shù),但此時(shí)并執(zhí)行 fn,執(zhí)行 bind 會(huì)有一個(gè)返回值,這個(gè)返回值就是就是把 fn 的 this 改變后的結(jié)果。體現(xiàn)了預(yù)處理思想。