Reputation: 1
everyone:
as we all know, getting a nonexistent value from Object will got a "undefined", is there any way to throw an error instead of return a undefined
?
for instance:
var a= {example:"example"};
//do something here
a.b //error throw instead of "undefined"
thx very much for helping.
Upvotes: 0
Views: 321
Reputation: 6882
Looking at the above example, if you are you trying to initialize the property "b" on the object a with a value after "a" has been defined, then you could just as easily do the following:
var a= {example:"example"};
//do something here
a.b = 'some value';
a.b //now an error is not throw
Most Objects can be re-defined even after they have been initialized. Properties and methods can be added and removed once objects have been initialized. I say most, because it is possible to prevent objects from being extended/altered (using Object.preventExtension method). https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions
Upvotes: 0
Reputation: 9422
ES6 comes with Proxy Objects which will help you overload the dot operator. What this means is that you can invoke a function when you retrieve a property. This will allow you to check if the property is defined and if it isn't "throw" an error. Hope this helps. More info here
Upvotes: 0
Reputation: 236
Object.define property has a way to specify the get and set methods
look at the link below
Object class has a method "hasOwnProperty" which could also be used to check if a property exists or not before trying to access it
Upvotes: 1