I hope you can give us some advice on the problems pointed to by this.

these two are learning the relevant syntax of ES6. When I learned about the this problem of the arrow function, when I compared it with the this in ES5, I found that the following line of code got incredible results:
var age = 77;

function foo() {
    var age = 18;
    setTimeout(function () {
        console.log(this.age);//undefined
    },3000)
}
foo();

clipboard.png

is there a big boss who knows the problem? My understanding is that this should output 77. But undefined is output here


you read it wrong. After a delay of 3 seconds, the output is 77. That's right.

clipboard.png

clipboard.png


knows what the problem is.
quotes an explanation from a great god.
when normal in a browser environment, the this in seTimeout actually points to window, output 77. It's different if you run it in a node environment. The node environment also has its own setTImeout timer, whose this points to the Timeout object, and the Timeout object does not have an age property, so it returns undefined. You can output this yourself and you'll see.

Menu