【发布时间】:2017-01-16 22:42:17
【问题描述】:
使用 ECMAScript 6,我可以这样写:
const {
a = mandatory('a'),
b: {
c = mandatory('c'),
d = mandatory('d')
} = mandatory('b')
} = { a: 'a', b: { c: 'c', d: 'd' } }
console.log(a, b, c, d)
function mandatory (field) {
throw new Error(`Not giving you a ReferenceError today, but you must set a non-falsy value to "${field}"!`)
}
mandatory 是一个使用“默认语法”的函数,并打算在属性设置为假值时抛出“已知”错误。
当我运行代码时,我得到一个ReferenceError: b is not defined。如果我删除 d: 'd' 它突然不会再抛出错误了。
... = { a: 'a', b: { c: 'c' } }
它会抛出 desired 错误:
Error: Not giving you a ReferenceError today, but you must set a non-falsy value "d"!
- 如何定义
b? - 如果
a.b设置为非虚假值,我如何调用mandatory并抛出我自己的错误?
【问题讨论】:
-
如果我删除
d: 'd'- 从哪里删除?这不在您发布的代码中。 -
您的代码在 Node 6.2.2 中对我来说可以正常工作。
-
抱歉,已修复。我添加了
d: 'd'。所以“ReferenceError”是不需要的,但“Error”是需要的。
标签: javascript node.js ecmascript-6