var name = "windowsName"; var a = { name: "Cherry", fn : function () { console.log(this.name); // Cherry } } a.fn();
1 2 3 4 5 6 7 8 9 10 11
var name = "windowsName"; var a = { name : null, // name: "Cherry", fn : function () { console.log(this.name); // windowsName } }
var f = a.fn; f();
1 2 3 4 5 6 7 8 9 10 11
var name = "windowsName";
functionfn() { var name = 'Cherry'; innerFunction(); functioninnerFunction() { console.log(this.name); // windowsName } }
fn()
Methods to change where this points
Arrow Function
this in arrow function points where the function is defined, instead of conducting.
If there is no this in arrow function, we must find the scope chain to find the value. if a non-arrow function contains the arrow function, this in the arrow function is the this in the non-arrow function, otherwise this is undefined.