samedi 25 juin 2016

Using closures or the underscore convention for private members

Douglas Crackford and many others suggest using closures for private members as follows:

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}

The upside of this is that these members are not accessible outside the constructor function, but the downside is that it's not possible to use the private members in the prototype. So you end up putting everything that uses the private members in the constructor, which is not good for memory purposes.

Some others recommend using underscores when naming the private members:

function Container(param) {
    this.member = param;
    this._secret = 3;
}

Container.prototype.dec = function {
    if (this.secret > 0) {
        this.secret -= 1;
        return true;
    } else {
        return false;
    }
}

The downside of this is that those members are easily accessible publicly, and the only thing stopping people is the convention.

My questions are:

  1. When do you decide to use one over the other?
  2. Is one way preferred more commonly than the other?
  3. What are some famous libraries that use one of these methods?
  4. Is there a better method than these two?

Aucun commentaire:

Enregistrer un commentaire