I am new to Javascript (i.e. learning Javascript CORRECTLY). I'm reading the section on "Static Private Variables" in the Professional Javascript for Web Developers 3rd Edition in Chapter 7.
I was presented with this code, but I feel it is not ideal:
(function(){
//private variables and functions
var privateVariable = 10;
function privateFunction(){
return false;
}
//constructor
MyObject = function(){
};
//public and privileged methods
MyObject.prototype.publicMethod = function(){
privateVariable++;
return privateFunction();
};
})();
In this case, they are relying on creating MyObject as a global variable by omitting "var". However, under strict mode, you cannot omit the var keyword and this code would cause an error.
Would my rewrite be correct?
var MyObject = (function(){
//private variables and functions
var privateVariable = 10;
function privateFunction(){
return false;
}
var MyObject = function (){
}
//public and privileged methods
MyObject.prototype.publicMethod = function(){
privateVariable++;
return privateFunction();
};
return MyObject;
})();
I'm confused about why the book would omit a solution to this issue and approach with a lazy methodology. I'm a strong believer in using "strict mode" for all my code.
window.MyObject.windowobject. The OP's rewrite is objectively better.