为什么这会在带有--harmony的Node.js中抛出错误?

时间:2015-06-22 19:32:00

标签: javascript node.js ecmascript-6 ecmascript-harmony

在Chrome Canary和Node.js 0.12.3中,以下代码打印p

  'use strict';
  let o = {
    name: 'o',
    foo: function() {
      ['1'].map(function() {
           console.log(this.name);
      }.bind(this));
    },
  };

  let p = { name: 'p' };

  o.foo.call(p); // p

在Chrome Canary中,以下代码也会打印p。但是为什么它会在Node.js 0.12.3中使用--harmony标志抛出TypeError?

  'use strict';
  let o = {
    name: 'o',
    foo: function() {
      ['1'].map(() => {
           console.log(this.name);
      });
    },
  };

  let p = { name: 'p' };

  o.foo.call(p); // p in Chrome, TypeError in Node.js with --harmony

换句话说,当第二个代码段在Node.js中运行时,为什么this undefined

1 个答案:

答案 0 :(得分:2)

这只是iojs和节点使用的due to a bug in the version of the V8 engine。 Chrome Canary使用V8的不稳定版本解决了这个问题。当这个修复版本推出到V8的稳定版本时,node / iojs应该以相同的方式工作。

目前,您可以使用babel之类的工具来转换代码。使用代码中没有标记的babel转换为:

function foo() {
  var _this = this;

  ['1'].map(function () {
    console.log(_this.name);
  });
}

确实打印p