es6类:如何省略"this"关键字

Mar*_*ria 2 javascript ecmascript-6 reactjs babeljs ecmascript-next

在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>
    }
}
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 6

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

除此之外没有办法做到这一点,因为this.name不应该与name变量混淆,省略this将是一个错误.

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

render() {
    const { name } = this;

    return <div>{name}</div>
}
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,您只能使用它来读取属性,如果要分配属性,仍然必须使用`this.name`. (3认同)