What is the value of “this” inside an arrow function that is defined inside a class [duplicate]

坚强是说给别人听的谎言 提交于 2019-12-13 10:53:23

问题


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?

For eg:

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

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


回答1:


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.

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 = () => {
            // ...
        };
    }
}



回答2:


In this case, the this keyword is just an instance of abc. For example:

var alphabet = new abc();
alphabet.testFunction();

class abc {
testFunction = () => {
    this.x = 30; // is the same as:
alphabet.x = 30;
}

Hope this helps! For more info on the this keyword, go to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



来源:https://stackoverflow.com/questions/48921462/what-is-the-value-of-this-inside-an-arrow-function-that-is-defined-inside-a-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!