es6 类:如何省略“this”关键字

IT技术 javascript reactjs ecmascript-6 babeljs ecmascript-next
2021-05-01 11:58:21

在 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>
    }
}
1个回答

这在with语句中是可能的,但由于它与严格模式不兼容,因此它在现代 JS 中没有value。

否则没有办法做到这一点,而且由于this.name不应与namevariable混淆,省略this将是一个错误。

如果this.name在 JSX 中影响可读性或者被多次使用,可以对属性进行解构:

render() {
    const { name } = this;

    return <div>{name}</div>
}