Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 class: how to omit "this" keyword

In ES6, is it possible to create local variables and just reference them directly, instead of adding this. in front, like this.name.

Example, in the code below, what can I do to make it possible to write {name} instead of {this.name} all the time. (Adding this. in front of variables is a bit cumbersome!)

class User extend React.Component {
    name = "Joe";

    render() {
        // is it possible to write {name} instead of {this.name}
        return <div>{name}</div>
    }
}
like image 304
Maria Avatar asked Jun 15 '18 00:06

Maria


1 Answers

This is possible with with statement, but since it isn't compatible with strict mode, it has no value in modern JS.

There's no way to do this otherwise, and since this.name shouldn't be confused with name variable , omitting this would be a mistake.

If this.name in JSX affects readability or is used many times, the property can be destructured:

render() {
    const { name } = this;

    return <div>{name}</div>
}
like image 65
Estus Flask Avatar answered Nov 07 '22 21:11

Estus Flask