{foo = foo} 解构安全模式的验证技巧是否可以采用?
Is the {foo = foo} validation trick in destructuring a safe pattern to adopt?
我在一个答案中读到了这个技巧 ,
可以像这样验证 foo
属性 的存在:
const {foo = foo} = bar
它抛出 Uncaught ReferenceError: Cannot access 'foo' before initialization when foo
is undefined
.
这是 JS 中定义明确的行为吗?这是否适用于所有最近的 JavaScript 版本和环境(浏览器、节点)以及未来可能的版本和环境?
我想看看如果我不关心更具体的错误消息,开始使用它作为方便的 shorthand 验证是否有意义。
谢谢。
Is this a well-defined behaviour in JS?
是的。它依赖于 const
和 let
变量的 。但是,如果将它们转换为 var
,它可能无法工作。
I am trying to see if it could make sense to start using this as a convenient shorthand validation
不,请不要。这真是一段晦涩难懂的代码,每个 linter 都会抱怨 use-before-define。即使您不关心特定的错误消息,至少使用
const {foo = error()} = bar;
使用抛出 error
函数来明确意图。
我在一个答案中读到了这个技巧 foo
属性 的存在:
const {foo = foo} = bar
它抛出 Uncaught ReferenceError: Cannot access 'foo' before initialization when foo
is undefined
.
这是 JS 中定义明确的行为吗?这是否适用于所有最近的 JavaScript 版本和环境(浏览器、节点)以及未来可能的版本和环境?
我想看看如果我不关心更具体的错误消息,开始使用它作为方便的 shorthand 验证是否有意义。 谢谢。
Is this a well-defined behaviour in JS?
是的。它依赖于 const
和 let
变量的 var
,它可能无法工作。
I am trying to see if it could make sense to start using this as a convenient shorthand validation
不,请不要。这真是一段晦涩难懂的代码,每个 linter 都会抱怨 use-before-define。即使您不关心特定的错误消息,至少使用
const {foo = error()} = bar;
使用抛出 error
函数来明确意图。