JS in this and pure object-oriented (java,c++) in the This is a little bit the same, because the scope is different, resulting in JS in the direction of this is ambiguous, this in Java refers to the current object of this or the current class of this, in JS function () {} There is no special specified this point, here the this point to window, but in strict mode, function () {return This} inside this is undefined, the arrow function inside this is window, Let's take a look at an example (for the sake of simplicity, the > in the code below is the console input,< is the output of the console):
//enter this function first in the console,functionPerson () { This. Age = 0; SetInterval (functionGrowup () {
This at this point points to window and does not point to the this.age above This. age++; },1000)}>var p = new person ()>p
Because this is pointing to window, it does not point to the this.age above, so it does not change
<person {age:0}
Age is a global variable, no initial value, and + + becomes not a Number>agenan
Assign an initial value to age, and the following will begin ++leage= 00 Age5 Age8 Age10 Age14 Age16
A solution that was popular in the past
//enter this function first in the console,functionPerson () {//define a local variable to put the current this inside, the following function can be usedLet that = This; This. Age = 0; SetInterval (functiongrowup () {//this at this point points to window and does not point to the this.age abovethat.age++; },1000)}//all normal >let p=NewPerson (); >p<person {age:0}>p<person {age:1}>p<person {age:2}>p<person {age:3}
Only this one solution? It's time for the arrow function to debut,the arrow function does not create its ownthis
, which uses the enclosing execution contextthis
values. Therefore, in the following code, pass to thesetInterval
within the function of thethis
with the enclosing function.this
The same value, simply put, the arrow function does not come with this, his this is from the previous level, so just good solution to this problem:
function Person () { this. Age = 0; = = {This// |this| correctly points to Person object },New 123 }
We'll read about chestnuts:
function f () {Console.log (this. a)}>f ()<undefined// at this point the call passes in the parameter, which can be understood as this, but it is not affected by this >f.call ({a:1})<1>f.apply ({a:1})<1
One more to remember, when an arrow function returns an object, {} is enclosed in parentheses, for example: F = () = = ({}), curly braces denote an object
More examples of arrow functions: API
The This and arrow functions in REACT:JS