JavaScript binds this in a global function as a global object, and uses the same interpretation for nested functions. Let's look at a piece of JavaScript code nested with two-layer functions:
The Code is as follows:
Var me = {
Name: 'jimbor ',
Blog: 'http: // jmedia.cn /',
SayMyName: function (){
Var pre = 'My name is :';
Function displayName (){
Alert (pre + this. name );
}
DisplayName ();
}
}
Me. sayMyName ();
From the code point of view, we want to display the name attribute of me through the call of sayMyName (), that is, My name is: Jimbor. But the browser's execution result is:
The Code is as follows:
My name is:
Why is the name attribute incorrectly displayed? Originally, JavaScript bound this in the global function as a global object, and used the same interpretation for nested functions. The consequence of this error is that you cannot easily use nested functions to complete some special tasks, because these functions have different interpretations of the objects this points.
Of course, for this example, we can complete the corresponding functions without nested functions. However, this structure may be required for some applications. Fortunately, we still have a way to correct this error.
Method 1: Use the apply () function
The Code is as follows:
Apply (this_obj, params_array)
The apply () function can override the object pointed to by this when calling a function. It accepts two parameters. The first this_obj is the object pointed to by this, params_array is the parameter array used to pass to the called function. We changed the original code:
The Code is as follows:
Var me = {
Name: 'jimbor ',
Blog: 'http: // jmedia.cn /',
SayMyName: function (){
Var pre = 'My name is :';
Function displayName (){
Alert (pre + this. name );
}
DisplayName. apply (me );
}
}
Me. sayMyName ();
Check the browser execution result again:
My name is: Jimbor
Similar functions include call (). The difference is that the call () method for passing parameters is one by one instead of packing them into an array.
Method 2: replace this with that
That is, we can define a variable in the outermost function to point to the object pointed to by this. Once the internal function needs to call this, we will use this defined variable. Normally, this variable is named that according to your habits. The original code can be changed to the following:
The Code is as follows:
Var me = {
Name: 'jimbor ',
Blog: 'http: // jmedia.cn /',
SayMyName: function (){
Var pre = 'My name is :';
Var that = this;
Function displayName (){
Alert (pre + that. name );
}
DisplayName ();
}
}
Me. sayMyName ();
Very easy to use, isn't it? Because it does not involve the specified object, we recommend the second method.