本文介绍了"this"的值是多少?在类内部定义的箭头函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新问题,但我想知道"this"的值对在javascript类中定义的箭头函数的含义是什么.

Newbish question but I was wondering what the value of "this" would be for an arrow function that is defined inside a javascript class.

它是对包含它的类的引用吗?

Is it a reference to the class enclosing it?

例如:

class abc {
    testFunction = () => {
        //What is the value of 'this' here?
    }
}

试图更好地理解这一点,以了解如何将函数传递给ReactJS中的组件.

Trying to understand this better to understand how functions are passed to components in ReactJS.

推荐答案

您已经标记了问题"ES6"(即ES2015),但请注意,类字段(您使用的语法)不在ES2015中.或ES2016或ES2017,而不会出现在ES2018中.尽管已通过转译在React社区中得到了广泛使用,但它仍然是Stage 3的提案.

You've tagged your question "ES6" (which is to say, ES2015) and such, but note that class fields (the syntax you're using) isn't in ES2015 — or ES2016, or ES2017, and won't be in ES2018. It's still a Stage 3 proposal, despite being in widespread use in the React community via transpilation.

根据该建议,字段初始化程序的this与构造函数中的相同:对新构造的实例的引用.该代码等效于:

With that proposal, this for the field initializers is the same as it would be in the constructor: A reference to the newly-constructed instance. That code is equivalent to:

class abc {
    constructor() {
        this.testFunction = () => {
            // ...
        };
    }
}

这篇关于"this"的值是多少?在类内部定义的箭头函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:44
查看更多