Thursday, January 25, 2018

How to set null context in call function?

Leave a Comment
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 ?

4 Answers

Answers 1

Quoting from MDN

if the method is a function in non-strict mode, null and undefined 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({});

Answers 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({});

Answers 3

http://es5.github.io/#x15.3.4.4

NOTE The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

In your case you are not in strict mode, if you set strict mode this can be set to anything you want. Be careful though, you can end up referencing things you do not want to by accident.

//global object being set, since this can't be null  function test(){                if(this === null){          console.log("This is null");       }else{           console.log("This is Object");       }   }  test.call(null);  test.call({});    //example of strict returning null  function test2(){    "use strict";       if(this === null){          console.log("This is null");       }else{           console.log("This is Object");       }   }  test2.call(null);  test2.call({});

Answers 4

without strict mode you can also check null and empty object using .type method

function test(x){               if(jQuery.type(x) === "null"){         console.log("This is null");      }else{          console.log("This is Object");      }  } test(null); test({}); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment