Dirk Smaverson
Dirk Smaverson

Reputation: 873

using closures to create private properties referenced in prototypes

I'm wondering if this is an accepted method of creating private properties to be referenced in prototypes of a new class in javascript. So instead of necessitating the creation of methods in the constructor like so:

function Bar(){ 
  var bar = 'bar';
  this.getbar = function(){
    return bar
  }
}

I want to put the getbar method in a prototype like so:

var Bar;
(function(){
  var bar = 'bar';
  Bar = function(){};
  Bar.prototype.getbar = function(){
    return bar;
  };
})();

Upvotes: 0

Views: 73

Answers (1)

LetterEh
LetterEh

Reputation: 26696

It's not going to be particularly useful to you.

var foo = new Bar();
var foo1 = new Bar();
var foo2 = new Bar();

Each one will have the exact same value in .getBar()

.prototype can NOT access private variables, at all, period.

What you've got there is really more like a static property than a private property of an instance.

If you want to do that, you need to create a public accessor, which you could then call from the prototype (or from any other part of your code, because it's public).

function Wallet (amount) {
    var balance = amount; // this will be unique to each wallet
    this.getBalance = function () { return balance; };
    this.addToBalance = function (amount) { balance += amount; };
    // these ***NEED*** to be in the constructor to have access to balance
}

Wallet.prototype.addFunds = function (amount) { this.addToBalance(amount); };
Wallet.prototype.checkFunds = function () { return this.getBalance(); };


var wallet = new Wallet(371.00);
wallet.addFunds(2.00);

Now your prototypes have access to public methods, which themselves have access to private variables.
...but why go through that trouble, to put it in the prototype, when you can just use the public methods of the instance (which is what I'm doing in the prototype, anyway) ?

The moral is, if an object only has publicly-facing data, then feel free to move all methods to the prototype.

But if there is any private-state at all, in any of the objects, then any methods which are supposed to have access to that state need to be in the constructor, and any methods which only use public state (ie: called with this) can be in the prototype.

Upvotes: 1

Related Questions