5

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.

7
  • 4
    This question probably belongs over at codereview.stackexchange.com - but I would consider your rewrite objectively more correct than the example from the book. Commented Oct 14, 2016 at 22:42
  • 5
    Your version is fine. That book is fairly old; 4 years is a huge span of time in the Web technology world. Commented Oct 14, 2016 at 22:42
  • Sorry! Was my first post on stackoverflow. If someone could move it to a more appropriately location that would be great! Commented Oct 14, 2016 at 22:44
  • 1
    A more acceptable way of explicitly creating a global would have been for the example to have assigned to window.MyObject. Commented Oct 14, 2016 at 22:57
  • 2
    @Pointy …though that's still not a declaration, and requires a global window object. The OP's rewrite is objectively better. Commented Oct 15, 2016 at 5:47

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.