james_womack
james_womack

Reputation: 10296

Using ES6 Arrow Functions in Node 0.11 w/ Foo.prototype

I'm getting what I see as unexpected behavior in using arrow functions inside a prototype extension.

function ES6Example(){}
ES6Example.prototype.foo = function(bar){
  return ((baz) => {
    console.log(this)
    this.bar = baz
  })(bar)
}

var es6Example = new ES6Example
es6Example.foo('qux')

console.info(es6Example.bar)

The above code results in the global context being printed out, as well as es6Example.bar being undefined. This is the old behavior. Based on the docs I've seen in MDN I expected this to be bound to the instance. I am running the above code using Node v0.11.15 using the harmony flag. Note that the following does work:

function ES6Example(){
    this.foo = baz => {
      this.bar = baz
    }
}

Upvotes: 1

Views: 172

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382150

V8 implementation is still incomplete, there's still no lexical this.

That's why, in Chrome node.js and io.js, you must set a special "harmony" parameter to use it : it's not ready for general consumption.

Upvotes: 2

Related Questions