Private methods and fields

I evaluate selfish and wonder how can I declare private methods / fields?

+5
source share
1 answer

The usual way to do private functions is to use a function that your various "methods" close, for example. choosing their example Dog, change this:

// The basic Dog example
var Dog = Base.extend({
  bark: function() {
    return 'Ruff! Ruff!'
  }
});

For

// Adding a private function
var Dog = Base.extend((function(){
  function trulyPrivate() {
    console.log(this.bark());
  }

  return {
    bark: function() {
      return 'Ruff! Ruff!'
    },
    logBark: function() {
        trulyPrivate.call(this);
    }
  };
})());

Using:

new Dog().logBark();  // logs "Ruff! Ruff!" using the truly private function behind the scenes

Re private fields, the usual way is to build something that requires truly private fields from your constructor function, so that they close the (private) variables in the constructor call, a'la Crockford Picture :

function Foo(arg) {
    var trulyPrivateData = arg;

    this.logIt = function() {
        console.log(trulyPrivateData);
    };
}

Using:

var f = new Foo(42);
f.logIt(); // logs 42 even though there no way, externally, to get that value from `f`

... , initialize :

var Dog = Base.extend({
  initialize: function(arg) {
    var woof = arg || 'Ruff! Ruff!';
    this.bark = function() {
        return woof;
    };
  }
});

woof ( , ), bark. , ( , bark ).

, ( ) , , .., this:

, Lineage , , , .. , .

+4

All Articles