如何使用babelify在ES6中正确绑定当前对象上下文 [英] How to properly bind current object context in ES6 using babelify

查看:184
本文介绍了如何使用babelify在ES6中正确绑定当前对象上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class SomeClass {

search()=> {...}

}

哪个是100%的合法代码,但是,babelify不想编译它

  SyntaxError:/ Users / vladmiller / Projects / test / test / client / test /app/pages/Search.react.js:解析文件时出现意外的令牌(50:26):/Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js\ 

相反,现在我必须在类构造函数中绑定上下文

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

哪个是相当烦人和无聊的。 >

UPD:原来,这是无效的ES6语法;所以问题如下。将实例上下文绑定到类方法的最佳方法是什么?



UPD2:默认情况下,应附加上下文,但是,反映 http://jsbin.com/citafaradu/2/edit?js,console,输出

解决方案

此代码无效ES2015。原型方法定义如下:

  class SomeClass {

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

}


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

解决方案

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

class SomeClass {

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

}

这篇关于如何使用babelify在ES6中正确绑定当前对象上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆