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?
JavaScript uses the null value to represent the intentional absence of any object value. If you find a variable or a function that returns null , it means that the expected object couldn't be created.
In JavaScript, null is a special value that represents an empty or unknown value. For example, let number = null; The code above suggests that the number variable is empty at the moment and may have a value later.
The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).
null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null . typoef operator is useful to determine the type of a variable (number, string, boolean).
The first argument for Function.prototype.call
is the context, which defines the this
value for the execution context of the invoked function, nothing else.
So basically, you're saying that this
is referring to null
(at least, in ES5 strict mode), but since you don't access this
anyway, it makes no difference.
In non-strict mode, this
cannot be null
, so it's replaced with the global object instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With