Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - Arrow vs classic method in ES6 class

Is there any reason to write classic syntax of ES6 methods?

class MyClass {

    myMethod() {
        this.myVariable++;
    }

}

When I use myMethod() as callback on some event, I must write something like this (in JSX):

// Anonymous function.
onClick={() => { this.myMethod(); }}

// Or bind this.
onClick={this.myMethod.bind(this)}

But if I declare method as arrow function:

class MyClass {

    myMethod = () => {
        this.myVariable++;
    }

}

than I can write just (in JSX):

onClick={this.myMethod}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The feature you are using is not part of ES6. It's the class fields proposal. It allows you to initialize instance properties without having to write a constructor. I.e. your code:

class MyClass {

    myMethod = () => {
        this.myVariable++;
    }

}

is exactly the same as

class MyClass {

    constructor() {
        this.myMethod = () => {
            this.myVariable++;
        };
    }

}

And this also shows you what the difference is between a normal class method an a method created via a class field:

  • A normal method is shared between all instances of the class (it is defined on the prototype)
  • A "class field method" is created per instance

So all the same as reasons as presented in Use of 'prototype' vs. 'this' in JavaScript? apply, but in short:

  • Use "class field methods" if you need a method per instance. Such is the case for event handlers that need to access the current instance. Access to this also only works if you are using an arrow function.
  • Use normal class methods in all other cases.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...