我彻底迷失了。
我有一个函数..
Number.prototype.abs = function () {
return this >= 0 ? this : this * -1;
};
..返回数字的绝对值..
(50).abs(); // 50
(-50).abs(); // 50
..但是比较不正确..
(50).abs() === 50; // False
..有时。
(50).abs() == 50; // True
(-50).abs() === 50; // True
它的问题是,它可以在 Chrome 12 和 Firefox 4 中运行,但不能在 IE 9、Safari 5 或 Opera 11 中运行。
我没有发现代码有任何问题,而且由于它可以在 Chrome 和 Firefox 中运行,因此它是特定于浏览器的,但我不知道是什么。
更新:浏览器的特定差异在于严格模式支持。我在严格模式下运行代码,这引入了一些使我的代码正常工作的更改。它在浏览器中失败的原因是它们的严格模式不完整或缺失。
为什么返回 false?
最佳答案
尽管Jeremy Heiler是正确的,他的理由被误解了。为什么你得到 object
而不是 number
与构造函数无关。
这里的问题是 this
关键字。您需要了解每当使用 this
时会发生什么。稍微深入研究一下 ECMA 草案就会告诉您这一点
The this keyword evaluates to the value of the ThisBinding of the current execution context.
(我会更改上面的内容。this
关键字不会计算出任何内容的值,我们很快就会看到。)嗯,好吧,但是如何ThisBinding
到底有效吗?继续阅读!
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:
- If the function code is strict code, set the ThisBinding to thisArg.
- Else if thisArg is null or undefined, set the ThisBinding to the global object.
- Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).
- Else set the ThisBinding to thisArg.
- Let localEnv be the result of calling NewDeclarativeEnvironment passing the value of the [[Scope]] internal property of F as the argument.
- Set the LexicalEnvironment to localEnv.
- Set the VariableEnvironment to localEnv.
- Let code be the value of F’s [[Code]] internal property.
- Perform Declaration Binding Instantiation using the function code code and argumentList as described in 10.5
这就是问题所在(看粗体部分)。如果从非对象上下文调用函数,ThisBinding
(也称为使用 this
)始终返回包装在对象内的上下文的值。解决这个问题最简单的方法是:
Number.prototype.abs = function () {
"use strict"; // if available
// * 1 implicitly coerces 'this' to a number value
return this >= 0 ? this * 1 : this * -1;
//... or Number(this) explicitly coerces 'this' to its toNumber value
return Number(this >= 0 ? this : this * -1);
};
...强制 this
对象(或强制严格模式)。但我认为了解 this
的工作原理很重要,这个问题就是一个很好的例子。
关于javascript - 50 === 50 : false. 50 == 50 : true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039265/