箭头与ES6类中的经典方法 [英] Arrow vs classic method in ES6 class

查看:169
本文介绍了箭头与ES6类中的经典方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有理由编写ES6方法的经典语法?

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

class MyClass {

    myMethod() {
        this.myVariable++;
    }

}

当我使用 myMethod()作为某些事件的回调,我必须写这样的东西(在JSX中):

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++;
    }

}

比我可以写的(在JSX):

than I can write just (in JSX):

onClick={this.myMethod}


推荐答案

您使用的功能不属于ES6。这是 类字段提案。它允许您初始化实例属性,而无需编写构造函数。即你的代码:

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:


  • 正常方法是共享的在类的所有实例之间(它在原型上定义)

  • 每个实例创建一个类字段方法

所以与在JavaScript中使用'prototype'与'this'中提供的原因完全相同? 适用,但简而言之:

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.

这篇关于箭头与ES6类中的经典方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆