相关疑难解决方法(0)

箭头函数与函数声明/表达式:它们是等效/可交换的吗?

规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.

ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?

例子:

构造函数

function User(name) {
  this.name = name;
}

// vs

const User = name => {
  this.name = name;
};
Run Code Online (Sandbox Code Playgroud)

原型方法

User.prototype.getName = function() {
  return this.name;
};

// vs

User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)

对象(文字)方法

const obj = {
  getName: function() {
    // ...
  }
};

// vs

const obj = {
  getName: () => {
    // ...
  }
};
Run Code Online (Sandbox Code Playgroud)

回调

setTimeout(function() {
  // ...
}, 500);

// vs

setTimeout(() => {
  // ...
}, …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 arrow-functions

449
推荐指数
2
解决办法
12万
查看次数

如何使用箭头函数(公共类字段)作为类方法?

我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:

class SomeClass extends React.Component {

  // Instead of this
  constructor(){
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  // Can I somehow do this? Am i just getting the syntax wrong?
  handleInputChange (val) => {
    console.log('selectionMade: ', val);
  }
Run Code Online (Sandbox Code Playgroud)

因此,如果我要传递SomeClass.handleInputChangesetTimeout它,那么它将被限定为类实例,而不是window对象.

javascript ecmascript-6 reactjs babeljs ecmascript-next

168
推荐指数
4
解决办法
8万
查看次数

在ES6中使用React类定义方法的两种方法有什么区别

我在ES6 React代码中看到了很多

class Foo extends React.Component {
  bar = () => {
    console.log("bar")
  }

  baz() {
    console.log("baz")
  }
}
Run Code Online (Sandbox Code Playgroud)

好像他们都定义方法barbazFoo,但他们如何不同.

ecmascript-6 reactjs

4
推荐指数
1
解决办法
217
查看次数