【发布时间】:2014-06-22 11:29:01
【问题描述】:
我在 Fedora 19 上安装了节点 v0.10.28 和 V8 v3.14.5.9。我遇到的问题是具有thisArg 可选参数的方法,例如Array.prototype.forEach。
如果我在 Chromium v33 或 Firefox v28 上执行以下代码 - jsFiddle
var y = [1, 2, 3];
y.forEach(function (element) {
console.log(this);
}, 'hej');
我得到一个输出
String {0: "h", 1: "e", 2: "j", length: 3}
String {0: "h", 1: "e", 2: "j", length: 3}
String {0: "h", 1: "e", 2: "j", length: 3}
然后是相同的代码,但处于严格模式 - jsFiddle
var y = [1, 2, 3];
y.forEach(function (element) {
'use strict';
console.log(this);
}, 'hej');
我得到一个输出
hej
hej
hej
这些是我根据 ECMA5 规范 sec-function.prototype.call 所期望的结果。
thisArg 值作为 this 值不加修改地传递。这是对第 3 版的更改,其中 undefined 或 null thisArg 被替换为全局对象,而 ToObject 应用于所有其他值,并且该结果作为 this 值传递。即使 thisArg 未经修改地传递,非严格模式函数在进入函数时仍会执行这些转换。
如果提供了 thisArg 参数,它将被用作每次调用 callbackfn 的 this 值。如果未提供,则使用 undefined 代替。
及相关伪代码
Let funcResult be the result of calling the [[Call]] internal method of callbackfn with T as thisArgument and a List containing kValue, k, and O as argumentsList.
然而,在节点上,上面的 sn-ps 都返回
{ '0': 'h', '1': 'e', '2': 'j' }
{ '0': 'h', '1': 'e', '2': 'j' }
{ '0': 'h', '1': 'e', '2': 'j' }
谁能确认这是我的节点环境的问题,还是节点的问题?
更新:只是为了确认,在节点typeof this 上的两种情况下都返回object。
【问题讨论】:
-
console.log(typeof this); -
@cookiemonster 在这两种情况下,它都显示为
object,而不是(严格)string和(非严格)object,这不是我所期望的。 -
是的,刚刚做了同样的测试。
this instanceof String是true。奇怪的。我无法想象 Node 本身与它有任何关系,除非 V8 中有某种方法可以完全禁用某些严格模式功能,即使在嵌套函数中也是如此。 -
其他严格模式功能似乎工作正常。
-
查看这个 V8 错误报告:code.google.com/p/google-caja/issues/detail?id=1501 似乎这是去年修复的。我的 Node 版本必须有旧的 V8。我正在运行 Node 0.10.24,因此它与您的版本非常接近,这似乎是最新的。
标签: javascript node.js strict