1

I'm trying to bind current instance to the class method, please note ES6 syntax.

class SomeClass {

  search() => { ... }

}

Which is 100% legit code, however, babelify doesn't want to compile it

SyntaxError: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js: Unexpected token (50:26) while parsing file: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js\

Instead, now I have to bind context in class constructor

class SomeClass {
  constructor() {
    this.search = this.search.bind(this)
  }
  search() { ... }
}

Which is quite annoying and boring.

UPD: It turns out that this is invalid ES6 syntax; therefore the question is follows. What is the best way to bind instance context to a class method?

UPD2: By default context should be attached, however, the issue with React http://jsbin.com/citafaradu/2/edit?js,console,output

Kirill Fuchs
  • 13,446
  • 4
  • 42
  • 72
Vlad Miller
  • 2,255
  • 1
  • 20
  • 38
  • Why do you think this was 100% legit code? It's coffeescript syntax, not ES6. – Bergi Jun 09 '15 at 07:59
  • I assumed that if ES6 support arrows this should actually work on class level as well https://babeljs.io/docs/learn-es2015/#arrows – Vlad Miller Jun 09 '15 at 08:32
  • And WebStorm didn't give me any warning on this syntax – Vlad Miller Jun 09 '15 at 08:33
  • Is there any better way to bind instance to class method? – Vlad Miller Jun 09 '15 at 08:34
  • *Instead now I have to bind context in class constructor*. No you don't, it's already bound. `search() { console.log(this) // logs SomeClass }` - assuming of course that the context of this hasn't been changed by the caller. [Example](https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=class%20SomeClass%20%7B%0A%20%20search()%20%7B%0A%20%20%20%20console.log(this)%3B%0A%20%20%7D%0A%7D%0Avar%20c%20%3D%20new%20SomeClass()%3B%0Ac.search()%3B%20%2F%2F%20Correct%20context%2C%20as%20it%20should%20be%20called%0Ac.search.call(window)%3B%20%2F%2F%20Modified%20context) – CodingIntrigue Jun 09 '15 at 11:49
  • @RGraham Here is a quick example, looks like with React context is not bind http://jsbin.com/citafaradu/2/edit?js,console,output – Vlad Miller Jun 09 '15 at 13:06
  • @VladMiller: Those babel docs don't use an arrow as part of a class body anywhere either? – Bergi Jun 09 '15 at 14:57
  • Well, no. It's just was confusing because in React docs it is stated that you can use arrow to bind the context. I think this question is closed now – Vlad Miller Jun 10 '15 at 01:29

1 Answers1

5

This code is not valid ES2015. Prototype methods are defined like this:

class SomeClass {

  search() { /* ... */ }

}
Pavlo
  • 43,301
  • 14
  • 77
  • 113