0

Consider this:

 var Foo = function Foo () { var numberVar = 0; fooPrototype = { getNumberVar: function () { return numberVar; }, setNumberVar: function (val) { this.numberVar = val; } } return fooPrototype; }; var foo = new Foo(); 

Alternatively, look at this:

 var Bar = function Bar() { var numberVar = 0; }; Bar.prototype = { getNumber: function () { return this.numberVar; }, setNumber: function (val) { this.numberVar = val; } }; var bar = new Bar(); 

They both do the same thing, in that they allow for public / private members. Is there any benefit to doing this one way or the other?

0

1 Answer 1

1

Your logic here is based on a faulty assumption. In your second implementation, the constructor variable numberVar is never used. You have no code that can reach it and thus you are not using a private variable in the second code block.

Your methods in that second implementation are accessing an object property named numberVar which is publicly accessible as a property on the object which is different than the local variable of the same name in your constructor. You cannot have private variables in your second implementation because your prototype-declared methods are not declared in a private scope.

Here's what happens in your second code block:

 var Bar = function Bar() { // this variable is never used as there is no code in this scope // that can reach this variable. In fact, it is garbage collected // immediately var numberVar = 0; }; Bar.prototype = { getNumber: function () { return this.numberVar; }, setNumber: function (val) { // sets a public property on the object this.numberVar = val; } }; var bar = new Bar(); bar.setNumber(10); console.log(bar.numberVar); // 10, this property is public 

For a general discussion of methods declared in the constructor vs. prototype-defined methods, see this discussion:

Advantages of using prototype, vs defining methods straight in the constructor?

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

2 Comments

Very well said! That post is exactly what I was looking for. Moreover, your second paragraph really helped me to understand what the issue was. Thank you.
Also found a great answer on how to create public / private methods while still using Prototype: stackoverflow.com/questions/1441212/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.