How to set null context in call function?
function test(){
if(this === null){
console.log("This is null");
}else{
console.log("This is Object");
}
}
test.call(null);
test.call({});
Output :
This is Object.
This is Object.
But I expect Output :
This is Null.
This is Object.
Why Null not set in context ?
Solution 1:
Quoting from MDN
if the method is a function in non-strict mode,
null
andundefined
will be replaced with the global object and primitive values will be converted to objects.
This explains why you get an object when you call test.call(null);
. When null
is passed here, this
inside test()
will be global object Window
.
For the desired behavior, use strict mode.
function test() {
"use strict";
if (this === null) {
console.log("This is null");
} else {
console.log("This is Object");
}
}
test.call(null);
test.call({});
Quoting from ES6 Specifications for strict mode
If
this
is evaluated within strict mode code, then thethis
value is not coerced to an object. Athis
value ofnull
orundefined
is not converted to the global object and primitive values are not converted to wrapper objects. Thethis
value passed via a function call (including calls made usingFunction.prototype.apply
andFunction.prototype.call
) do not coerce the passed this value to an object
Solution 2:
What does the 'this' indicate? you can use console.log(this);
to know it. But as answer, use an input (here I called it input
) and test it.
function test(input){
if(input=== null){
console.log("This is null");
}else{
console.log("This is Object");
}
}
test(null);
test({});