1

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
    }
}
hippietrail
  • 15,848
  • 18
  • 99
  • 158
james_womack
  • 10,028
  • 6
  • 55
  • 74

1 Answers1

2

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • `this` gets passed through if I assign to foo inside the constructor. It only doesn't work in prototype. – james_womack Jan 25 '15 at 18:28
  • 1
    What you see is the same `this` than with normally bound contexts. The lexical `this` isn't yet implemented. The arrow function is also said buggy, you should wait for the V8 team to finish it in my opinion. – Denys Séguret Jan 25 '15 at 18:32
  • 2
    Adrian Perez at Igalia is implementing arrow functions in v8. He is very close to landing the final patch for handling `this`, but there are just a few breakages in TurboFan to iron out: https://codereview.chromium.org/883823002/ – Andrew Paprocki Jan 28 '15 at 03:17