简体   繁体   English

JavaScript样式:不要将包装器对象用于基本类型

[英]JavaScript style: don't use wrapper objects for primitive types

In the Google JavaScript style guide, it says not to use wrapper objects for primitive types. 在Google JavaScript样式指南中,它表示不对原始类型使用包装器对象。 It says it's "dangerous" to do so. 它说这样做是“危险的”。 To prove its point, it uses the example: 为证明其重点,它使用了以下示例:

var x = new Boolean(false);
if (x) {
  alert('hi');  // Shows 'hi'.
}

OK, I give up. 好的,我放弃了。 Why is the if code being executed here? 为什么if代码在这里执行?

因为每个变量, typeof Object是truthy和包装都是对象。

if(x) will run if x is truthy. if(x) x是真的, if(x)将运行。

x is truthy if it's not falsey. 如果不是假的话, x是真的。

x is falsey if x is null , undefined , 0 , "" , false 如果x为nullundefined0""false ,则x为false

So since new Boolean(false) is an Object and an Object is truthy, the block runs 因此,因为new Boolean(false)是一个Object而一个Object是真实的,所以该块运行

In the if(x) case, it's actually evaluating the default Boolean of the object named and not its value of false . if(x)情况下,它实际上是在评估所命名对象的默认布尔值而不是其值false

So be careful using Boolean objects instead of Boolean values. 所以要小心使用Boolean对象而不是Boolean值。 =) =)

The following code uses a Boolean object. 以下代码使用Boolean对象。 The Boolean object is false, yet console.log("Found") still executes because an object is always considered true inside a conditional statement. Boolean对象为false,但仍然执行console.log("Found")因为在条件语句中对象始终被视为true。 It doesn't matter that the object represents false; 对象表示错误并不重要; it's an object, so it evaluates to true. 它是一个对象,因此它的计算结果为true。

var found = new Boolean(false);
if (found) 
{    console.log("Found");
       // this executes
}

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

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