问题
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