您只能在调用函数时执行此操作,通常使用Function#call
or Function#apply
:
function foo() {
console.log("name = " + this.name);
}
var obj = {name: "Fred"};
foo.call(obj); // Outputs "Fred"
在那里,我们使用 调用foo
函数,作为调用期间使用的值call
传入。obj
this
将其应用于 DOM 元素:
function foo() {
console.log("My id is " + this.id);
}
var elm = document.getElementById("whatever");
foo.call(elm); // "My id is whatever"
asthis
在调用期间使用的值是call
and的第一个参数apply
。两者之间的唯一区别是您如何将参数传递给函数(foo
在我们上面的示例中):使用call
,您将它们作为后续离散参数传递:
theFunction.call(thisArg, firstArg, secondArg, thirdArg);
使用apply
,你给它一个args数组:
var args = [firstArg, secondArg, thirdArg];
theFunction.apply(thisArg, args);
// or (of course)
theFunction.apply(thisArg, [firstArg, secondArg, thirdArg]);
// Note -------------------^-----------------------------^
所以一个更完整的例子:
function foo(firstArg, secondArg, thirdArg) {
console.log("name = " + this.name);
console.log("firstArg = " + firstArg);
console.log("secondArg = " + secondArg);
console.log("thirdArg = " + thirdArg);
}
var obj = {name: "Fred"};
// These two calls do exactly the same thing:
foo.call(obj, "one", "two", "three");
foo.apply(obj, ["one", "two", "three"]); // Note the [ and ]