jeudi 15 octobre 2015

Declaring private static member variable in JavaScript

I am stuck with a design pattern in JavaScript where I would like to create a private static member variable for keeping object count. Something along these lines:

var person = function(name){
    //How to persist this value across multiple calls avoiding Globals
    var _personCount = _personCount || 0;
    _personCount++;
    var _name = name;
    getPerson = function(){
          return "Person is: " + _name;
    }
};

person("foo");//_personCount should be 1 after this call
person("bar");//_personCount should be 2 after this call

The idea is something to similar to private static variables, accessible only to the class's internal variables

Aucun commentaire:

Enregistrer un commentaire