Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Private Variables in Javascript

Tags:

javascript

oop

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.

like image 275
Even Steven Avatar asked Nov 09 '22 07:11

Even Steven


1 Answers

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/

like image 146
Martin Chaov Avatar answered Nov 15 '22 07:11

Martin Chaov