Static private variables in javascript

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.

+5
source share
1 answer

Yes, your correspondence is correct. However, I would advise you to change the book. This is a really good series: https://github.com/getify/You-Dont-Know-JS

This book provides very beautiful examples and uses + explanations: https://addyosmani.com/resources/essentialjsdesignpatterns/book/

+1
source

Source: https://habr.com/ru/post/1258236/


All Articles