Some methods of one of my classes right now are public, but can access private variables (they are privileged). This is because they are created in the class constructor, so their closure has access to the object closure.
What I would like to avoid, though, is the memory and performance overhead of creating new privileged methods every time. So I want to share them.
Is there any way to put privileged methods into a prototype?
Example was requested:
function Person(age) { // age is private
this.grow = function() { // grow is now public, but can access private "age"
age += 1;
}
}
dan = new Person(10);
dan.grow();
dan.age; // undefined
This works, I have a public method "grow" that can access the private variable "age", but grow has to be recreated for each object.
The more performant way is:
function Person(age) { // age is private
this.age = age; // but this.age is public
}
Person.prototype.grow = function() {
this.age += 1;
}
dan = new Person(10);
dan.grow();
dan.age; // 11
This shares the "grow" method, but now age is public.