I've got the following (simplified) Batman.js
file:
(function(){
"use strict";
window.Batman = function(){
// Global references
this.version = "1.0.1";
};
Batman.prototype.saveGotham = function(params) {
var _ = this; // Works fine
destroyGotham.call(_, params);
};
// Private
function destroyGotham(params){
var _ = this; // <!-- "possible strict violation"
}
}());
JSHint complains about a possible strict violation
at the indicated line. How do I get around this without dropping the "use strict"
?
P.S: I'd like the troublesome var _ = this
to reference the Batman
instance.
The value passed as this
to a function in strict mode is not forced into being an object.
For a normal function, this
is always an object, and it's the global object if called with an undefined or null this
, in other words this
is usually the window
by default in non-strict mode.
Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality that "secure" JavaScript environments must restrict.
Thus for a strict mode function, the specified this
is not boxed into an object, and if unspecified, this
will be undefined by default.
This means that using this
that way, just setting it to a variable
var _ = this;
in most cases will lead to this
being undefined, which why jshint is saying it's a "possible" violation, as it would be if you didn't call it with call
and provided a this-value.
Ignore jshint, what you're doing is fine.