[英]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
. 如果
X
是undefined
则typeof
检查只会返回{}
。
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.