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.
.