javascript - 50 === 50 : false. 50 == 50 : true?

标签 javascript

我彻底迷失了。

我有一个函数..

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:

  1. If the function code is strict code, set the ThisBinding to thisArg.
  2. Else if thisArg is null or undefined, set the ThisBinding to the global object.
  3. Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).
  4. Else set the ThisBinding to thisArg.
  5. Let localEnv be the result of calling NewDeclarativeEnvironment passing the value of the [[Scope]] internal property of F as the argument.
  6. Set the LexicalEnvironment to localEnv.
  7. Set the VariableEnvironment to localEnv.
  8. Let code be the value of F’s [[Code]] internal property.
  9. 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/

相关文章:

javascript - 无论是否附加了 Chrome 调试器,日期构造函数的工作方式都不同

javascript - Iscroll mousewheel 滚动在 firefox 中比 Google Chrome 慢

javascript - 在 Angular Directive(指令)中使用 require 更新 $watch

javascript - 当我用 <div> 附加它时,Bootstrap 下拉菜单不起作用

javascript - 谷歌云函数http触发foreach循环的问题

javascript函数默认原型(prototype)与对象实例

javascript - 带条件的 jquery 验证插件规则?

javascript - 使用正则表达式进行算术

javascript/jquery 从 url 中删除相对路径

javascript - 有选择地将对象数组字符串化为 JSON