The content of this article is about parsing this in Js by example. Friends in need can refer to it
A few days ago when I was looking at the interview questions, I saw this program:
obj = { name: 'a', getName: function () { console.log(this.name); } }; var fn = obj.getName;obj.getName();fn();
The required questions are executed herefn()
The result and the pointing problem of this
during execution. Let's re-summarize the use of this based on this example and the questions therein.
The direction of this is determined according to its execution environment. There are mainly the following situations:
The global environment is outside any function. If this is used, this refers to the global object. For example, in the browser:
this === window // true
In the function context environment, that is, when calling this inside the function, it depends on how this is called.
In a simple call, this in the function points to the global object, for example:
function myFun() { console.log(this === window); } myFun(); // true
In the above example, the function myFun# is called directly ##, where
this is equal to the global object
window.
The principle is that when declaring the function
myFun, it
exists as an attribute of the global object. Therefore, when this function is used directly, it is equivalent to calling window.myFun(), that is, when it is called as a property of
window,
this points to
window.
obj.getName() is executed, this in the function points to the object obj. So the output is
a.
But when we separate this function separately, change the initial example:
function myFun() { console.log(this.name); }var obj = { name: 'a', getName: myFun }; obj.getName(); // avar obj2 = { name: 'b', fun: myFun }; obj2.fun(); // b
this to The above is the detailed content of Example parsing this in Js. For more information, please follow other related articles on the PHP Chinese website! depends entirely on The closest member reference
, which object and reference the function is bound to, then this will have different points. In the above example, we bound the functions with this to different objects as their methods, then the corresponding this is bound to different objects,
this.name# The value of ## is different. Similarly, when we execute
myFun()
directly, this function is called as a property of the global object window
. Therefore, the myName
attribute cannot be found and undefined
is output. (Because the global object
window has the default attribute name
is an empty string, myName
is used here as an example)function myFun() {
console.log(this.myName);
}
myFun(); // undefined
fn
, so executing fn
is equivalent to executing window.fn()
, that is, this anonymous function initially initialized as the property of obj is bound to the fn
property of window
, so its this
Points to window
. The
name
attribute of window
is an empty string, so the output is empty. Related recommendations: