Based on my understanding of javascript, prototype methods cannot access variables that are private to the scope of the constructor,
var Foo = function() {
var myprivate = 'I am private';
this.mypublic = 'I am public';
}
Foo.prototype = {
alertPublic: function() { alert(this.mypublic); } // will work
alertPrivate: function() { alert(myprivate); } // won't work
}
It makes perfect sense, but is there any way around this that is safe and good practice? Since using prototypes provides a performance benefit in that the member functions are allocated only once, I'd like to achieve a similar functionality while still being able to get to my private variables. I don't think it will work by using a prototype, but is there another pattern, such as a factory method or a closure approach? Something like,
var fooFactory = function() {
var _alertPrivate = function(p) { alert(p); } // bulk of the logic goes here
return function(args) {
var foo = {};
var myprivate = args.someVar;
foo.mypublic = args.someOtherVar;
foo.alertPrivate = function() { _alertPrivate(myprivate); };
return foo;
};
}
var makeFoo = new fooFactory();
var foo = makeFoo(args);
I'm not sure whether a new copy of _alertPrivate is created each time I create a new Foo or if there is any potential performance benefit. The intention is to get a functionality similar to prototyping (inasmuch as it saves memory) while still being able to access private variables.
Thanks.