Having trouble getting the following to pass jslint/jshint
/*jshint strict: true */
var myModule = (function() {
"use strict";
var privVar = true,
pubVar = false;
function privFn() {
return this.test; // -> Strict violation.
}
function pubFn() {
this.test = 'public'; // -> Strict violation.
privFn.call(this); // -> Strict violation.
}
return {
pubVar: pubVar,
pubFn: pubFn
};
}());
myModule.pubFn();
I understand it's being caused by the use of this
in a function declaration, but I read something Crockford wrote and he said the violation is meant to prevent global variable pollution - but the only global variable here is the one I'm explicitly defining... myModule
. Everything else is held in the immediate function scope, and I should be able to use this
to refer to the module.
Any ideas how I can get this pattern to pass?
Update: if I use a function expression instead of a declaration, this seems to work, ie
var pubFn = function () { ...
I'm not a fan of this format though, prefer to have the function name and named params closer and the declaration looks/feels cleaner. I honestly don't see why this is throwing the violation - there's no reason for it in this pattern.
JSHint has an option called
validthis
, which:Use it in the function that JSHint is complaining about, which in your case, would look like this:
It might seem like a pain to have to specify that in each function where it applies, but if you set the option at the top of your module function, you may hide genuine strict mode violations from yourself.
The real problem here is that if you call
privFn
from within the module context (from within the IIFE),this
will beundefined
when in strict mode;window
if not in strict mode. Alas, the function would fail if called from within the IIFE.This is because the functions have no owner (object) when called from within an IIFE, whereas the returned module object is the owner of the functions when they are called from outside the IIFE context, e.g.
this === myModule
when callingmyModule.pubFn()
.Both strict mode and JSHint/JSLint are trying to help you and you should never just ignore the errors/warnings generated by them, but instead figure out why they are warning you.
If you are 100 percent sure that
privFn
,pubFn
, etc. will not be called anywhere but outside your module, just put in the comment/*jshint validthis: true */
in any functions that generate a warning. Alternatively, one comment in the IIFE will prevent JSHint from generating this error on any function inside the module.One of the many possible solution
Store the scope of
this
(inself
in this example) to refer explicitly to the module. This will show and ensure your intent.Unfortunately, this is the intended error for this setup since jslint/jshint don't know the function declared in global context is to be later used as an object method.