In Javascript, the value of this
is dependent on the way you call the function.
There are 5 ways to call a function in JS, and they all have effect on this
:
new Foo();
<= here, you’re creating a new object, andthis
will reflect that new objectFoo();
<= here, you’re calling the function as-is, andthis
will be the global object(!)var obj = { foo: Foo };
<= here, you’re calling the function as a method of
obj.foo();obj
;this
will beobj
Foo.call(thisObject, arg1, arg2);
<= here, you can specify the value ofthis
in the first argumentFoo.apply(thisObject, [args]);
<= here, you can specify the value ofthis
in the first argument
In 4 and 5, the difference between call and apply is that with call
, you need to pass all the arguments separately, whereas with apply
, you can pass an array containing all the arguments.
Note that in my example 2 above, the function should have been called foo
instead of Foo
. Since it’s impossible to know off-hand whether a function is supposed to be called with new
or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new
); otherwise, it should start with lowercase.