0

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.

Aether W
  • 1
  • 1
  • Looking at the above example, are you trying to initialize the property "b" on the object a with a value. – Don Oct 16 '15 at 02:52
  • only in firefox can you catch unknown key access like that (methodmissing-style) – dandavis Oct 16 '15 at 03:02

3 Answers3

1

Object.define property has a way to specify the get and set methods

look at the link below

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Object class has a method "hasOwnProperty" which could also be used to check if a property exists or not before trying to access it

Praveen
  • 206
  • 2
  • 11
  • set and get method is for given keys, it still not able to throw an error when using `var v= a.b` if b is not a key of a. – Aether W Oct 16 '15 at 05:37
0

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

Community
  • 1
  • 1
Bhargav Ponnapalli
  • 9,224
  • 7
  • 36
  • 45
0

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

Don
  • 6,632
  • 3
  • 26
  • 34
  • sorry , i do not means to add a value or function for given object, instead, i want an error to be throw when i try to attach a "undefined" value in object. – Aether W Oct 16 '15 at 05:40
  • If that's the case then as Praveen mentioned, you need to use Object.defineProperty and add your validation logic in the setter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set – Don Oct 16 '15 at 05:44
  • can i clone an Object class, and overwrite the dot operator(`.`) by some way in ES5? – Aether W Oct 16 '15 at 05:49
  • What do you mean by overwrite dot operator? Can you provide some sample code to demonstrate what it is that you are trying to achieve? – Don Oct 16 '15 at 05:57