我想使用 javascript apply() 方法调用一个函数。如果函数没有参数,这就可以正常工作。即
function test()
{
console.log(this);
}
body = document.getElementsByTagName("body")[0]; // shortcut to body element
test.apply(body); // returns [object HTMLBodyElement]
但我似乎不能做同样的事情来调用一个有参数的函数:
function test(msg)
{
console.log(msg);
}
body = document.getElementsByTagName("body")[0]; // shortcut to body element
test(this).apply(body); // mysteriously returns the correct result, then
// typeError: 'undefined' is not an object (evaluating "test(this).apply".
上面的示例完全是微不足道的,但我的问题的重点是:如何使用 apply() 方法调用带参数的函数。
最佳答案
apply
接受两个参数:
test.apply(null, [body]);
第一个参数在执行函数时设置 this
的值。第二个是该函数的参数数组。
在您的示例中,您可以按如下方式重写它:
function test() {
console.log(this);
}
并按如下方式调用它:
test.apply(this);
关于javascript - 在 JavaScript 中使用参数调用 apply 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7676768/