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?
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. Usingbabel
with no flags on your code transpiles to:Which does indeed print
p
.