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.
Yes, your rewrite is correct. I would advice you to change the book however. This is a really good series: https://github.com/getify/You-Dont-Know-JS
This book provides very nice examples and usage + explanations: https://addyosmani.com/resources/essentialjsdesignpatterns/book/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With