Why does this throw an error in Node.js with --harmony?

196 views Asked by At

In Chrome Canary and Node.js 0.12.3, the following code prints 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

In Chrome Canary the following code also prints p. But why does it throw a TypeError in Node.js 0.12.3 with the --harmony flag?

  '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

Put another way, why is this undefined when the second code snippet is run in Node.js?

1

There are 1 answers

0
Explosion Pills On BEST ANSWER

This is simply due to a bug in the version of the V8 engine that iojs and node use. Chrome Canary uses an unstable version of V8 that has addressed this issue. When this fixed is rolled out to a stable version of V8, node/iojs should work the same way.

For now, you can use a tool like babel to transpile your code. Using babel with no flags on your code transpiles to:

function foo() {
  var _this = this;

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

Which does indeed print p.