The real problem here is that if you call privFn
from within the module context (from within the IIFE), this
will be undefined
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 calling myModule.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
(in self
in this example) to refer explicitly to the module. This will show and ensure your intent.
/*jshint strict: true */
var myModule = (function() {
"use strict";
var privVar = true,
pubVar = false,
self = this;
function privFn() {
return self.test;
}
function pubFn() {
self.test = 'public';
//privFn.call(this); // Will have no effect, as `privFn` does not reference `this`
privFn();
}
return {
pubVar: pubVar,
pubFn: pubFn
};
}());
myModule.pubFn();