I have an Object
with a getter and setter where I'm intending to protect a property so that it can only be updated through a method. Let's call this object Person
which has the following structure:
function Person(data) {
var _name = data.name;
this.name = function () {
return _name;
};
this.setName = data.setName || function (newValue) {
_name = newValue;
};
}
I want to be able to override setName
and pass different implementations to each instance of Person
but I can't quite seem to get it to work. I'm certain this is a closure issue, but I just can't get my head around it.
Given the following usage scenario, what am I doing wrong?
var p1 = new Person({
name: "Paul",
setName: function (newValue) {
this._name = newValue;
}
});
var p2 = new Person({ name: "Bob" });
p1.setName("Paul (updated)");
p2.setName("Bob (updated)");
p1
never updates its value and so is always "Paul" whereas p2
does and becomes "Bob (updated)". I want to be able to create as many unique instances of Person
as I want, where some of them have their own implementation of setName
and others will just use the default instance.
I've tried wrapping data.setName
up in a closure like this and setting my custom setName
to return the value instead:
this.setName = data.setName ? function () {
return (function (value) {
value = data.setName();
}(_name));
} : function (newValue) { _name = newValue; }
But I'm having no luck - I obviously just don't get closures as well as I thought! Any and all help always appreciated.