Let's say we have this script.
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
///more functions here....
}
How can I let all these functions run in strict mode? I can put "use strict" at the top of the file but JSlint does not approve this. An alternative is to put "use strict" in every function, but is there a better option?
Wrap everything inside an IIFE and JSLint should approve.
(function () {
"use strict";
//all your code here
}());
Note that variables/functions previously declared in the global scope would no longer be accessible in the global scope when moved to inside this immediately-invoked function expression.
You will have to explicitly set these as properties of the global object, e.g. the window
object for browser environment:
(function () {
"use strict";
window.someGlobalVariable = "something";
}());
@zzzzBov's solution also works nicely on both browser and back-end environments.