function fn1(){ console.log(1); } function fn2(){ console.log(2); } fn1.call(fn2); // 輸出1 fn1.call.call(fn2); // 輸出2
看到這個題目,第一反應是蒙圈的。函數
fn1.call(fn2);
這個是理解的。fn1.call.call(fn2);
這個蒙圈了。this
有些繞,須要多唸叨唸叨琢磨琢磨。spa
call
方法是Function.prototype
原型上天生自帶的方法,全部的函數均可以調用的。prototype
我以爲 call
方法自己沒有具體return
什麼出來,因此是undefined
。code
Function.prototype.call=function call(context){ // [native code] // call方法的功能 // 1. 把指定函數中的this指向context // 2. 把指定函數執行 // 那麼call方法中的this,即爲指定函數。也就是說 // 1. 把this中 的 this關鍵字指向context; // 2. 把指定函數執行this(); };
按照上面的理解blog
因此調用的是 fn1 ,此時fn1中的 this 指向的是 fn2。
可是這個方法裏面並無使用this,而是直接輸出了1。ip
按照上面的理解原型
因此調用的是 fn2(這裏有些繞,多唸叨唸叨琢磨琢磨),此時fn1.call中的this指向的是fn2。
它改變了call方法(Function.prototype原型上的call)的this指向。
此處調用了call方法中的this,即調用了fn2,輸出了2。it