Let's look at a section of JavaScript code that has nested two-level function:
Copy Code code 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, we want to display the Name property of me through the invocation of Saymyname (), namely: my name Is:jimbor. But the result of the browser's execution is:
Copy Code code as follows:
What causes the Name property to not display correctly? Originally, JavaScript is bound to this global object in global functions, and the same explanation is used for nested functions. The consequence of this error is that you cannot easily use nested functions to perform certain special tasks, because these functions do not interpret the object that this is pointing to.
Of course, for this example, we can do without nested functions to complete the corresponding functions. However, this structure may be required for some applications. Fortunately, we still have a way to correct this mistake.
Method One: Use the Apply () function
Copy Code code as follows:
Apply (This_obj, Params_array)
The Apply () function can override the object it points to when calling a function, it accepts two parameters, and the first this_obj wants to override the object pointed to by this, Params_array is an array of arguments to pass to the calling function. We'll rewrite the original code as:
Copy Code code 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 ();
Then look at the browser execution results:
My name Is:jimbor
A similar function also has call (). The difference is that call () parameters are passed one after another rather than packaged into an array.
Method Two: Replace this with that
That is, we can define a variable at the outermost function to point to the object that this is pointing to, and we use this defined variable once the internal function needs to call this. It is customary to name this variable as that. Then the original code can be changed like this:
Copy Code code 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 ();
It works, doesn't it? Because no specific object designation is involved, the second method is more recommended.