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?
In non-strict mode,
this
has undergone anObject(this)
transformation, so it's always truthy. The exceptions arenull
andundefined
which map to the global object. Sothis
is nevernull
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.The specification of ES5 says:
The
this
keyword shouldn't ever be null, but it might not be what you expect. You can end up referencing thewindow
object if you're not careful.In your case, I believe
this
should refer to thedoSomething
function.Here's a jsFiddle.
You can see what occurs if you try to force Javascript to use a null scope in any browser. I made an example here:
http://jsfiddle.net/rXsWj/
In short, this empirically proves that the browser changes 'null' to 'window' on the fly. If instead you change null to 'a', you'll see an alert of 'a' like you would expect. Code from link as reference:
No. The value of
this
will never be the text'some default value'
.this
can not be null. if it was null, then you couldn't be in method scope.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.