I wanted to invoke a function using the javascript apply() method. This works fine if the function has no arguments. i.e.
function test()
{
console.log(this);
}
body = document.getElementsByTagName("body")[0]; // shortcut to body element
test.apply(body); // returns [object HTMLBodyElement]
But I can't seem to do the same thing to invoke a function that has arguments:
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".
The examples above are completely trivial but the grain of my question is: How do I use the apply() method to invoke a function with arguments.
apply
takes two arguments:
test.apply(null, [body]);
The first argument sets the value of this
when the function is executed. The second is an array of parameters for that function.
In your examples you could rewrite it as follows:
function test() {
console.log(this);
}
and call it as follows:
test.apply(this);