this points to the this point in the 4 arrow function

The this point of the arrow function

You can learn from ES6 entry

The this object in the function body is the object where it is defined, not the object where it is used

How to understand this sentence

//如果不特意绑定 this name这个this 就会指向这个方法对应的域里面的this
let o = {
    
    
	returnDoSth() {
    
    
        console.log(this)//o 这个对象
         return () => {
    
    
             console.log(this)//o 这个对象
         }
     }
 }
 let dosth = o.returnDoSth()
 dosth()// o 这个对象
//绑定this后
let o = {
    
    
	returnDoSth() {
    
    
        console.log(this)// window
         return () => {
    
    
             console.log(this)// window
         }
     }
 }
 let dosth = o.returnDoSth.call(window)
 dosth()

//第二个例子
function foo() {
    
    
	console.log(this)
}
foo.call({
    
     id: 42 });//打印结果:   {id: 42}
foo()//打印结果: window

Summary: In the arrow function, if there is no intentional change (call apply bind, etc.) the direction of this, then this points to the this of the domain at the time of definition

//阮一峰 ES6 入门例子
function foo() {
    
    
  return () => {
    
    
    return () => {
    
    
      return () => {
    
    
        console.log('id:', this.id);
      };
    };
  };
}

var f = foo.call({
    
    id: 1});
//这个操作之后 foo()里面的this 就指向了{id:1},
//而所有箭头函数都在这里面定义,
//所以每个箭头函数下的 this 都是指向{id:1}了

var t1 = f.call({
    
    id: 2})()(); 
var t2 = f().call({
    
    id: 3})(); 
var t3 = f()().call({
    
    id: 4}); 

The arrow function is fixed and immutable. It is not possible to modify this even if you use call apply bind after the definition (the this of the arrow function always points to the this at the time of definition)

Due to the immutability of this arrow function, it is not suitable for defining methods inside objects, and it contains this

It is not recommended to use this when you need to dynamically bind this, such as event binding


end
personal humble opinion, if wrong, please correct me

Guess you like

Origin blog.csdn.net/Chennfengg222/article/details/104693941