简体   繁体   English

声明对象的两个语句之间的区别

[英]Difference between two statements that declare an object

What is the difference between this statement 这句话有什么区别

var X = X || {};

And this. 和这个。 They do the same thing? 他们做同样的事情吗? There is a performance difference? 有性能差异吗?

var X = typeof X === "undefined" ? {} : X;

They're not the same. 他们不一样。

The || || will return the object when X is any possible falsy value. X任何可能的值时,将返回该对象。
The typeof check will only return {} if is X is undefined . 如果Xundefinedtypeof检查只会返回{}

According to this test , the undefined check is nearly twice as fast. 根据此测试undefined检查几乎快了一倍。 That's probably because no type casting is required. 那可能是因为不需要类型转换。

In this case: var X = X || {} 在这种情况下: var X = X || {} var X = X || {} the X variable will be redefined if it's been declared but is falsy . var X = X || {}如果X变量已声明但为falsy,则会重新定义。 So var X = 0; X = X || {}; 因此var X = 0; X = X || {}; var X = 0; X = X || {}; would overwrite the 0 with an object. 会用一个对象覆盖0

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

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