为什么不应该使用Number作为构造函数? [英] Why should you not use Number as a constructor?

查看:1237
本文介绍了为什么不应该使用Number作为构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSLint中输入了这个语句:

I entered this statement in JSLint:

var number = new Number(3);

并收到以下讯息:


不要使用Number作为构造函数。

Do not use Number as a constructor.

为什么?语句是创建一个数字对象,而不是一个原始值,所以我不明白为什么使用 new 是一个问题。

Why is that? The statement is creating a number object, not a primitive value, so I don't see why using new is a problem.

编辑:感谢所有回复。他们让我进一步思考,因此我在这里发布了一个后续问题。

Thanks for all the responses. They've got me thinking further, so I posted a follow-up question here.

更新:再次感谢所有回应!他们一直非常有帮助。我想总结一下,在JavaScript中,对象类型不等于另一个对象类型,即使它们具有完全相同的值,除非它们都是EXACT SAME对象。

UPDATE: Thanks again for all the responses! They've been very helpful. I guess to sum up, in JavaScript, an Object type is not equal to another Object type, even when they have the exact same value, unless they are both the EXACT SAME object.

换句话说,在下面的Matthew的例子中,n1 == n2是false,因为你正在比较两个REFERENCES到两个SEPARATE对象,但n1 == n1是真的,因为你正在比较引用到EXACT SAME对象。

In other words, in Matthew's example below, n1 == n2 is false because you are comparing two REFERENCES to two SEPARATE objects, but n1 == n1 is true because you are comparing references to the EXACT SAME object.

所以,虽然我现在明白为什么使用Number作为构造函数可能会导致问题,我发现你可以在比较Number对象时使用valueOf属性。

So, while I now understand why using Number as a constructor can cause problems, I found you can use the valueOf property when comparing Number objects.

换句话说,n1.valueOf == n2.valueOf是true! (这是因为您要比较valueOf FUNCTION的返回值,而不是REFERENCES的对象本身的返回值。)

In other words, n1.valueOf == n2.valueOf is true! (This is because you're comparing the return values of the valueOf FUNCTION, not the REFERENCES to the objects themselves.)

推荐答案

除了打破===和typeof返回对象,使用Number构造函数也改变了该值在布尔上下文中的使用方式。因为new Number(0)是一个对象,而不是文字值,所以它的值为true,因为它不为null。例如:

In addition to breaking === and typeof returning "object", using the Number constructor also changes the way the value is used in boolean contexts. Since "new Number(0)" is an object, not a literal value, it evaluates as "true" because it is not null. So for example:

var n1 = 0;
var n2 = new Number(0);

n1 == n2  // true
n1 === n2 // false
if (n1) {
    // Doesn't execute
}
if (n2) {
    // Does execute, because n2 is an object that is not null
}

编辑:在数字文字和数字对象之间打破===甚至更糟,==甚至不能在两个Number对象之间工作以直观的方式 - 他们测试身份,而不是平等)。

Even worse than breaking === between number literals and Number objects, == doesn't even work between two Number objects (at least not in the intuitive way -- they test for identity, not equality).

var n1 = new Number(3);
var n2 = new Number(3);

alert(n1 == n2); // false
alert(n1 === n2); // false

这篇关于为什么不应该使用Number作为构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆