I have a Class that has a private variable with a public setter/getter function:
function Circle(rad) {
var r = rad;
this.radius = function(rad) {
if(!arguments.length) return r;
r = rad;
return this;
}
}
var shape = new Circle(10);
console.log( shape.radius() ); // 10
shape.r = 50;
console.log( shape.radius() ); // 10
How can I replicate this using Object.prototype? Or, when would I want to use a closure instead of Object.prototype? This is the closest I could come up with, but as you can see, you can change the property directly.
function Circle(r) {
this.r = r;
}
Circle.prototype.radius = function(r) {
if(!arguments.length) return this.r;
this.r = r;
return this;
};
var shape = new Circle(10);
console.log( shape.radius() ); // 10
shape.r = 50;
console.log( shape.radius() ); // 50
If you’re going to use the prototype to store an object’s properties, they are accessible from any code that has a reference to the object. It’s impossible to do what you want.
What many JS devs do is just name private properties with a leading underscore so that others know not to mess with it, but it doesn’t give you any real protection beyond a suggestion
Reasons to use closure based approach
Reasons to use prototype
Readers: Please edit the answer with reasons for whatever you think is the best solution.