How to properly bind current object context in ES6 using babelify

喜夏-厌秋 提交于 2019-12-13 00:29:30

问题


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


回答1:


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

class SomeClass {

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

}


来源:https://stackoverflow.com/questions/30726162/how-to-properly-bind-current-object-context-in-es6-using-babelify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!