Javascript 面试题随笔之Function.call.call
今天无聊在群里面看到了一道面试题:
1 function f1()
2 {
3 alert("1");
4 }
5 function f2()
6 {
7 alert("2");
8 }
9 var f3=f1.call;
10 f3.call(f2);
2 {
3 alert("1");
4 }
5 function f2()
6 {
7 alert("2");
8 }
9 var f3=f1.call;
10 f3.call(f2);
输出结果是2,后来想了一下,实在是让我大感JS的有趣,我的理解也不一定是正确的,只是想说出来,望有高手指正:
我是这么理解:
call函数是Function.prototype里面的函数,他在f1.call的情况下能调用f1,所以他的实现应该至少可以类似于
Function.prototype.call = function(thispointer, arg1, arg2)
{
thispointer = thispointer || window;
thispointer.func = this;
thispointer.func(arg1, arg2);
delete thispointer.func;
}
{
thispointer = thispointer || window;
thispointer.func = this;
thispointer.func(arg1, arg2);
delete thispointer.func;
}
当f1.call.call(f2)被调用时,实际上的执行过程是:
thispointer = f2;
f2.func = f1.call;
f2.func();
delete f2.func;
所以可以得到是f2.call()被调用了。就这样子。
thispointer = f2;
f2.func = f1.call;
f2.func();
delete f2.func;
所以可以得到是f2.call()被调用了。就这样子。