1

I am reading Nicholas C. Zakas's JavaScript for Web Developers Third Edition (old, I know), and I am having trouble understanding why static private variables/functions are static in the first place. I understand that if I declared a constructor with private variables/functions, all of its instances would have their own private variables/functions, like in one of Zakas's examples:

function MyObject(){

    //private variables and functions 
    var privateVariable = 10;

    function privateFunction(){ 
        return false;
    }

    //privileged methods 
    this.publicMethod = function (){
        privateVariable++;
        return privateFunction(); 
    };
}

So how would putting private variables/functions in private scopes make the variables static? Is it just because they're enclosed in a private scope, or is there something I'm overlooking? Here's one of Zakas's examples on static private variables:

(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();
   }; 
})();
1
  • 3
    I think your question is rhetorical. why static variable is static? Commented Jan 9, 2017 at 7:11

1 Answer 1

2

In your first example, every time you call MyObject a new local variable privateVariable is created.

In your second example, privateVariable is part of function(){ ... }, which is only called once, so only one variable is ever created. This one variable is used by MyObject.prototype.publicMethod, which is then shared by all objects created through MyObject.

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

1 Comment

Ah, that makes sense. So it's because the private members in the second example are not actually in the constructor (and that's why they only get called once)?

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.