This article explains in detail the this keyword in js. this always points to the owner object of the current function, and this can always determine its specific direction at runtime and its calling object. After graduation, I began to work hard for the transfer. I want to work hard. Come on. This article is based on the JS core series: the scope of functions.
In a function, this always points to the owner object of the current function. this always determines its specific point at runtime and its calling object.
Window. name = "window"; function f () {console. log (this. name);} f (); // output windowvar obj = {name: 'obj '}; f. call (obj); // output obj
When f () is executed, the caller of f () is a window object, so "window" is output ".
F. call (obj) is to put f () on the obj object for execution, which is equivalent to obj. f (). In this case, this in f is obj, so the output is "obj ".
Code1:
Var foo = "window"; var obj = {foo: "obj", getFoo: function () {return this. foo ;}}}; var f = obj. getFoo (); console. log (1 + ":" + f (); // Output window
Code2:
Var foo = "window"; var obj = {foo: "obj", getFoo: function () {var that = this; return function () {return that. foo ;}}}; var f = obj. getFoo (); console. log (f (); // output obj
Code1:
Run var f = obj. getFoo () to return an anonymous function, which is equivalent:
Var f = function (){
Return this. foo;
}
F () is equivalent to window. f (), so this in f points to the window object, and this. foo is equivalent to window. foo, so f () returns "window"
Code2:
Run var f = obj. getFoo () to return the same anonymous function, that is:
Var f = function (){
Return that. foo;
}
The only difference is that this in f changes to that. Before you know which object that is, determine the scope chain of f: f-> getFoo-> window and search for that in the chain. At this time, you can find that refers to this in getFoo, and this in getFoo points to the caller at runtime, from var f = obj. getFoo () indicates that this points to the obj object, so that. foo is equivalent to obj. foo, so f () returns "obj ".
For those who are not clear about the scope chain, refer to JavaScript from scope to closure.
The above is a detailed understanding of the this keyword in Js. For more information, see other related articles in the first PHP community!