In ES6, the problem of this pointing in arrow functions

The introduction of arrow functions in ES6 will not be explained here. Recently, this point about arrow functions is very confusing.

First, this in an arrow function always points to the outer object

The following example:

var x = 11 ;
var obj = {
    x:22,
    say:()=>{
        console.log(this.x);
        }
    }
obj.say(); //11

This is a very simple example. This in the arrow function say points to the outer object. Some bloggers call it the parent object, which is window.x. Some children may ask why not the x in obj, because say It is a property in obj, not an object, so this arrow function is defined in the object obj. There is no outer object of obj, only window, so this in the arrow function points to window.x

Look at the following example

var a = 11;
function test(){
    this.a = 22;
    let b =()=>{console.log(this.a)}
    b();
    }

var x = new test ();  // 22

The instantiated x this points to x, so this.a=xa is 22, and the value of window.a is still 11, slightly modified

var a = 11;
function test(){
    this.a = 22;
    let b =()=>{console.log(this.a)}
    b();
    }

 test();  //22

Change the instantiation to directly execute the test function. When executing this.a=22, overwrite window.a=11 with window.a=22. This in the arrow function still points to window, so the result is 22, window.a The value of has changed

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167055&siteId=291194637