简体   繁体   English

为什么选项[“ foo”] || options.foo?

[英]Why do options[“foo”] || options.foo?

Reading through the knockout.js source code I come accross this line 仔细阅读我在这条线上看到的基因敲除.js源代码

disposeWhenOption = options["disposeWhen"] || options.disposeWhen

I've never seen this before and everything I know about javascript says there is no case when the two sides of the || 我以前从未见过这种情况,而我所了解的关于javascript的一切都说,当||两侧都没有出现这种情况 would be different. 会有所不同。 Why might have the knockout team used this construct? 为什么淘汰赛团队会使用这种结构?

This comes as a result of symbol mangling performed by the Closure Compiler. 这是由Closure Compiler进行符号处理的结果。 From the Closure Compiler docs : Closure Compiler docs中

Closure Compiler compilation never changes string literals in your code, no matter what compilation level you use. 无论您使用哪种编译级别,Closure Compiler编译都不会更改代码中的字符串文字。 This means that compilation with ADVANCED_OPTIMIZATIONS treats properties differently depending on whether your code accesses them with a string. 这意味着,根据代码是否使用字符串访问属性,使用ADVANCED_OPTIMIZATIONS进行编译对属性的处理方式有所不同。 If you mix string references to a property with dot-syntax references, Closure Compiler renames some of the references to that property but not others. 如果将对属性的字符串引用与点语法引用混合在一起,则Closure Compiler重命名该属性的某些引用,但不重命名其他引用。 As a result, your code will probably not run correctly. 结果,您的代码可能无法正确运行。

Using both the dot syntax and the string literal is the "safe" way to work around this, as it helps ensure a client using an unexported part of the API but not using the closure compiler on their own code will not have any problems. 使用点语法和字符串文字都是解决此问题的“安全”方法,因为这有助于确保使用API​​的未导出部分但不对自己的代码使用闭包编译器的客户端不会有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM