Even Steven
Even Steven

Reputation: 137

Static Private Variables in Javascript

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.

Upvotes: 5

Views: 182

Answers (1)

Martin Chaov
Martin Chaov

Reputation: 864

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/

Upvotes: 1

Related Questions