Reputation: 1337
Often I have this situation:
var obj = { field: 2 };
and in the code:
do_something( obj.fiel ); // note: field spelt wrong
ie The property is incorrectly typed. I want to detect these bugs as early as possible.
I wanted to seal the object, ie
obj = Object.seal(obj);
But that only seems to prevent errors like obj.fiel = 2;
and does not throw errors when the field is simply read.
Is there any way to lock the object down so any read access to missing properties is detected and thrown?
thanks, Paul
EDIT: Further info about the situation
Upvotes: 2
Views: 2058
Reputation: 1275
There is no reliable getter/setters in javascript right now. You have to check it manually. Here's a way to do that:
if (!('key' in object)) {
// throw exception
}
Upvotes: 0
Reputation: 964
I don't think this will work in Javascript since objects are written like JSON and thus properties will be undefined or null but not throw an error.
The solution will be writing a native getter/setter.
var obj = {
vars: {},
set: function(index, value) {
obj.vars[index] = value;
},
get: function(index) {
if (typeof(vars[index]) == "undefined") {
throw "Undefined property " + index;
}
return vars[index];
}
};
Upvotes: 1