Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 'this' ever be null in Javascript

I have a function along the lines of the following:

    doSomething: function () {         var parent = null;          if (this === null) {             parent = 'some default value';         } else {             parent = this.SomeValue();         }     } 

Could parent ever be set to 'some default value' or is the check for null superfluous?

Alternatively, what if I used the less restrictive:

    doSomething: function () {         var parent = this ? this.SomeValue() : 'some default value';     } 

Could parent ever be set to 'some default value' in this case?

like image 929
Mark Robinson Avatar asked Mar 16 '12 15:03

Mark Robinson


People also ask

When can you use null in JavaScript?

'Null' in JavaScript 'Null' is a keyword in JavaScript that signifies 'no value' or nonexistence of any value. If you wish to shred a variable off its assigned value, you can simply assign 'null' to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript.

How do you handle null in JavaScript?

Falsy equality using == One way to check for null in JavaScript is to check if a value is loosely equal to null using the double equality == operator: As shown above, null is only loosely equal to itself and undefined , not to the other falsy values shown.

How check object is null or not in JavaScript?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .


2 Answers

In non-strict mode, this has undergone an Object(this) transformation, so it's always truthy. The exceptions are null and undefined which map to the global object. So this is never null and always truthy, making both checks superfluous.

In strict mode, however, this can be anything so in that case you'd have to watch out. But then again you have to opt in for strict mode yourself, so if you don't do that there are no worries.

(function() {               return this; }).call(null); // global object (function() { "use strict"; return this; }).call(null); // null 

The specification of ES5 says:

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.

like image 160
pimvdb Avatar answered Sep 23 '22 01:09

pimvdb


Although not a direct answer to your question.. in a browser 'this' will, by default, refer to the 'window' object. On nodejs it will refer to the global object.

I'm not sure if there's ever a case where it could be null, but it would at the very least be unusual.

like image 45
Evert Avatar answered Sep 26 '22 01:09

Evert