I’ve read that using Object.prototype to attach functions to custom JavaScript objects is more efficient than the “traditional” method of this.foo = function(). The problem I’ve run into is scope. I want these public methods to be able to access private variables of the object. What I ended up doing was this:
function Foo(){
var id = 5;
Foo.prototype.bar = function(){
alert(id);
};
}
var x = new Foo();
x.bar();
I nested the prototype declaration inside the object definition. This works and seems to solve the problem. Is there any reason to NOT do this? Is there a better or more standard way to accomplish this?
UPDATE
Based on some of the responses I’ve received I guess I need to mention that I’m fully aware that there is no concept of a private variable in JavaScript. I use the term private here meaning not accessible outside the current scope because it’s easier to say and write and I assume that anyone trying to answer this question would know what was meant by me using the term private.
While your idea works, it may not be working as you expect. I believe your overwrites the prototype each time a new
Foois instantiated. It would potentially change thebar()method for all instances ofFooeach time you create a newFoo. Oops.Here’s an example of using fake private variables for someone to “lie” about their real age.
Here is the standard way to do this: