Call apply method with arguments in JavaScript-Collection of common programming errors
First notice that you are actually invoking your function immediately, the line:
test(this).apply(body);
Fails because at first, you call the test
function passing this
as an argument, and then you try to access an apply
property on the function’s result, which is undefined
since your function doesn’t return anything.
That property access on the undefined
value is giving you the TypeError
exception.
Now, let’s see what you actually want to do, if you want to pass the value of the body
variable as the argument of your function, setting the outer this
value, as the this
value of test
, you can do:
test.apply(this, [body]);
But that’s why the call
method exists, when you know exactly which arguments to pass, you don’t need to create an array for nothing, you just pass the arguments:
test.call(this, body);
The apply
method is really useful when you deal with for example a dynamic number of arguments, when you know which arguments want to pass, and still have the ability of setting the this
value, call
is just what you need.
Originally posted 2013-11-09 22:41:48.