我正在阅读MSDN上的JavaScript .call()方法并看到以下代码:
function callMe(arg1, arg2){
var s = "";
s += "this value: " + this;
s += "<br />";
for (i in callMe.arguments) {
s += "arguments: " + callMe.arguments[i];
s += "<br />";
}
return s;
}
document.write("Original function: <br/>");
document.write(callMe(1, 2));
document.write("<br/>");
document.write("Function called with call: <br/>");
document.write(callMe.call(3, 4, 5));
// Output:
// Original function:
// this value: [object Window]
// arguments: 1
// arguments: 2
// Function called with call:
// this value: 3
// arguments: 4
// arguments: 5
从这份文件中我了解到.call()
的目的是:
call方法用于代表另一个对象调用方法。 它允许您从中更改函数的此对象 thisObj指定的新对象的原始上下文。
有问题的主要代码是:
document.write(callMe.call(3, 4, 5));
为什么这会将3
作为this
值返回?那个全球对象怎么样?
答案 0 :(得分:2)
因为.call()
的第一个参数是您正在调用的函数中this
的值。在您的情况下,即3
。