Why does the following work:
function sum(a,b) { return a + b; }
var result = sum.call(null,3,4); // 7
Why is result defined? I am invoking sum as a method of null. But null is not an object and cannot have properties!
What is going on?
Why does the following work:
function sum(a,b) { return a + b; }
var result = sum.call(null,3,4); // 7
Why is result defined? I am invoking sum as a method of null. But null is not an object and cannot have properties!
What is going on?
Its not. NULL in this case specifies to what object the
this
keyword is bound to. In your method, by setting it to NULL it will either not have athis
variable binding or it will be bound to the function itself or the window.Since you're not using any variables or functions that are accessed via
this
, then there's no need to use the call method ... you can just usesum(3,4)
As stated in, for example, MDN, the first argument is
The first argument for
Function.prototype.call
is the context, which defines thethis
value for the execution context of the invoked function, nothing else.So basically, you're saying that
this
is referring tonull
(at least, in ES5 strict mode), but since you don't accessthis
anyway, it makes no difference.In non-strict mode,
this
cannot benull
, so it's replaced with the global object instead.As the MDN explained.
Simply put it by a little code.
In the strict mode ,this is null. But in the not strict mode . this is window or global object.
When you use
.call
or.apply
withnull
orundefined
, the defaultthis
(usuallywindow
) is automatically used instead if not in strict mode.From MDN (emphasis mine):
If you are in strict mode, it actually will be
null
orundefined
.