Problems pointed to by this

var a=11
function test1(){
  this.a=22;
  let b=function(){
    console.log(this.a);
  };
  b();
}
var x=new test1(); //11 

my understanding of this function is that this points to the value in the calling environment. So the b function should be called in test1. It should be 22.
what"s the problem

?
Aug.07,2021

console.log (this.a); is executed in anonymous function b, pointing to window (pointing to undefined


in strict mode

this points to the caller or window, and the arrow function is what you want it to look like

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

Brother although you are a let declaration, when you call it, it is equivalent to a window call, so it is 11. If you really want to change it, you can use call or apply to change the this direction.


this points to the location where the function is executed, and whether there is any explicit or implicit binding, otherwise take the default window
solution: show binding b.call (this);. , or use the arrow function


to call new first, so the first this points to the object coming out of new, and the second this is called directly. For more information on pointing to the global variable window or global
, please see https://codeshelper.com/a/11.

.
Menu