说我有一些对象
> var a = {'a': 1, 'b': 2}
undefined
> a.c
undefined
如果这个“未定义”属性 c
改为引发某种自定义错误,我会很高兴。
是否有某种方法可以覆盖我的对象的默认行为,或者以某种方式调用它以在查找返回 undefined
时提供回调?
我找到了 this question from a couple of years ago这似乎是相关的。
我问是因为我觉得一般的 TypeError: cannot call method 'foo' of undefined
错误可能会被更有意义的反馈所取代。
最佳答案
您将以一种或另一种方式测试错误。重写它没有多大意义,尤其是因为您只会使代码库更加复杂,而 undefined 在这里实际上是有意义的。属性 c
从字面上看是 undefined ,因此这非常易读(尤其是对于使用您的代码的新手而言):
if (a.c) { //or could be a.c !== undefined,
//but if(a.c) will catch other falsey values
a.c.something();
}
关于javascript - 用自定义异常替换 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20845152/