【发布时间】:2018-11-24 20:12:41
【问题描述】:
在 ES6 中,是否可以创建局部变量并直接引用它们,而不是在前面添加this.,如this.name。
例如,在下面的代码中,我可以做些什么来让写{name} 而不是{this.name} 成为可能。 (变量前面加this.有点麻烦!)
class User extend React.Component {
name = "Joe";
render() {
// is it possible to write {name} instead of {this.name}
return <div>{name}</div>
}
}
【问题讨论】:
-
你试过了吗?
-
在每个使用它的函数的顶部,你可以
const { name } = this;我想 -
我不认为
this很麻烦。它使您的代码更加清晰。您可以轻松区分实例变量和局部变量。 -
她可能来自C++,将成员变量放在所有方法的范围内。
-
请注意,
name = "Joe";不是 ES6。 @Barmar:Java 也是这样工作的。
标签: javascript reactjs ecmascript-6 babeljs ecmascript-next