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,
thishas undergone anObject(this)transformation, so it’s always truthy. The exceptions arenullandundefinedwhich map to the global object. Sothisis nevernulland always truthy, making both checks superfluous.In strict mode, however,
thiscan 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: