I am new to Javascript (i.e., learning Javascript CORRECTLY). I read the "Static Private Variables" section in Professional Javascript for Web Developers 3rd Edition in Chapter 7.
I was introduced to this code, but I feel that it is not perfect:
(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 rely on creating MyObject as a global variable, omitting "var". However, in strict mode, you cannot omit the var keyword, and this code will throw an error.
Will my rewrite correctly?
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 am confused by why the book omits the solution to this problem and fits with a lazy methodology. I strongly believe in using strict mode for all of my code.
source share