Start by using getter and setter functions rather that using the properties directly:
var fruitType = {
"apple": 0,
"orange": 1
};
var fruit = function(name) {
this.setName(name);
};
fruit.prototype.getName = function(){
return this.name;
}
fruit.prototype.setName = function(name){
if (name in fruitType) {
this.name = name;
} else {
throw "wrong fruit type";
}
};
You could still override f.name
directly, but so long as you are consistent and use your setters you won't run into problems.
var f = new fruit("apple");
f.setName('orange'); // OK
f.setName('toast'); // Throws an error
f.name = 'toast'; // This works, so don't do it!
JSFiddle (Thanks The Dark Knight)
If it is important that f.name = 'toast'
does not work for you then you can use separate functions for every fruit object along with a privately scoped name
variable:
var fruitType = {
"apple": 0,
"orange": 1
};
var fruit = function(name) {
this.getName = function(){
return name;
}
this.setName = function(newName){
if (newName in fruitType) {
name = newName;
} else {
throw "wrong fruit type";
}
};
this.setName(name);
};
This has the disadvantage of every fruit needing it's own copies of the functions, but it has the advantage that the only way to modify the name
variable is using the setter:
var f = new fruit("apple");
f.setName('orange'); // OK
f.setName('toast'); // Throws an error
f.name = 'toast'; // This sets the `name` property to 'toast', but:
f.getName(); // this will still return 'orange'
JSFiddle