Force JavaScript exception/error when reading an undefined object property?

后端 未结 7 1184
后悔当初
后悔当初 2020-11-30 04:29

I\'m an experienced C++/Java programmer working in Javascript for the first time. I\'m using Chrome as the browser.

I\'ve created several Javascript classes with fie

7条回答
  •  时光取名叫无心
    2020-11-30 05:10

    Is there any way to force an error or exception to be thrown when I read an undefined property?

    In short, no. You can always test for whether or not you ended up with undefined by either comparing to undefined, like you said, or by attempting to access a second level attribute:

    s = Foo()
    
    s.bar = 1
    
    s['Bar'] // returns undefined.
    
    s['Bar']['Baz'] // Throws TypeError, s.Bar is undefined.
    

    Additionally, undefined fails in a conditional check, so you can get away with this as a shorthand for the comparison:

    if (s['Bar']) {
      // Something here only if s['Bar'] is set.
    }
    

    Be aware that this short hand could cause unexpected behavior if s['Bar'] was set, but was a 'Falsey' value, and you were only concerned with whether or not it came back undefined.

提交回复
热议问题