Call apply method with arguments in JavaScript

dkugappi picture dkugappi · Oct 6, 2011 · Viewed 29.5k times · Source

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.

Answer

John Keyes picture John Keyes · Oct 6, 2011

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);