Let's look at a piece of JavaScript with nested two-layer functions. Code :
Copy code Code: 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:Copy codeThe 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 () functionCopy codeThe 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:Copy codeCode: 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:Copy codeCode: 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.