JavaScript nested functions (scope chain) _javascript tips

Source: Internet
Author: User
Nested functions (Scope chain)
When you are nesting a function, be aware that the actual scope chain is changing, which may not seem intuitive. You can put the following code into the Firebug monitoring value changes.
Copy Code code as follows:

var testvar = ' Window property ';
var O1 = {testvar: ' 1 ', fun:function () {alert (' O1: ' +this.testvar+ ' << ');};
var O2 = {testvar: ' 2 ', fun:function () {alert (' O2: ' +this.testvar ';}};
O1.fun (); ' 1 '
O2.fun (); ' 2 '
O1.fun.call (O2); ' 2 '

This is the first example of this article.
Copy Code code as follows:

var testvar = ' Window property ';
var O3 = {
TestVar: ' 3 ',
TESTVAR2: ' 3** ',
Fun:function () {
Alert (' O3: ' +this.testvar);//' Obj3 '
var inner = function () {
Alert (' O3-inner: ' +this.testvar);//' Window properties '
Alert (' O3-inner: ' +this.testvar2);//undefined (not defined)
};
Inner ();
}
};
O3.fun ();

Here we change the other function, which is almost the same as the original function, but the difference is the internal function. Note that the scope where the internal function is run is not the same as the scope of the external function. Ext lets you specify the scope of the function when you call the function, avoiding scope problems.
Declaration of variables
You must add the "var" keyword when you initialize the variable, which is not a global variable. For instance, in the following example, there is a variable written inside the function, but you intend to declare a local variable, but it is possible to overwrite the value of the global variable. In the Firebug "DOM" tab, you can see all the global variables by detecting "window". If you find a "K" or "x" variable that proves that you are assigning this variable to an inappropriate scope. See the following example:
Copy Code code as follows:

var i = 4;
var j = 5;
var k = 7;
var fn = function () {
var i = 6;
K = 8;//Note there is no Var in front of this sentence to the meaning of the 8 given to the variable K!
alert (i);//6
Alert (j);//5
Alert (k + '-1 ');//8-1
x = 1;//The effect of this sentence is in two cases, create all the variable x or overwrite (overwrite) all variable x
};
FN ();
Alert (k + '-2 ');//8-2 (note not 7-2)

Unlike the previous example, it is noted that there is no var keyword in the function k, so instead of declaring a local variable, it assigns a value to K as a global variable. Also note that, during the alert method execution, the parameter i is the current local variable to be found, its value is 6, but the parameter J cannot be found in the current scope and is looked up along the scope chain (scope chain) until the global variable is found.
Specify Scope in Ext
As mentioned earlier, Ext has the flexibility to handle scope problems when calling functions. Some of the content comes from DJ posts.
When calling a function, you can think of this as a special (hidden) parameter within each function. At any time, JavaScript will put this in the function itself. It is based on a very simple idea: if a function is directly a member of an object, then the value of this is the object. If the function is not a member of an object then the value of this is set to a global object (commonly, a Window object in the browser). The following internal function can clearly see this idea.
A function, if assigned to a variable, that is not a member of any object, then the parameter of this becomes a Windows object. The following is an example that can be pasted directly into the Firebug console:
Copy Code code as follows:

var obj = {
Tostring:function () {return ' obj ' within scope (scope) ';},//rewrite the ToString function to facilitate execution of the console.log (this) output
Func:function () {
The function here is directly subordinate to the object "objects"
Console.log (this);
var innerfunc = function () {
n the function here is not a direct member of a particular object, but a variable of another function.
Console.log (this);
};
Innerfunc ();
}
};
Obj.func ();
Output "within the scope of obj (in scope)"
Output "Some of the relevant content of window ..."

The need to save is to call an argument like this-but you can also change the this argument artificially, except for a slightly different syntax. Change the last line of "Obj.func ();" To:
Copy Code code as follows:

Obj.func.call (window);
Output "Some of the relevant content of window ..."
Output "Some of the relevant content of window ..."

As you can see from the example above, call is actually another function (method). Call belongs to a system built for Obj.func (the function is an object, according to the characteristics of JavaScript). )。
By changing this to the scope of this point, we can continue to use an example to correct the This parameter in the Innerfunc--"incorrect" point:
Copy Code code as follows:

var obj = {
Tostring:function () {return ' obj ' within scope (scope) ';},//rewrite the ToString function to facilitate execution of the console.log (this) output
Func:function () {
The function here is directly subordinate to the object "objects"
Console.log (this);
var innerfunc = function () {
n the function here is not a direct member of a particular object, but a variable of another function.
Console.log (this);
};
Innerfunc.call (this);
}
};
Obj.func ();
Output "within the scope of obj (in scope)"
Output "within the scope of obj (in scope)"

Scope Configuration of Ext
As you can see, a function that does not have a scope assigned to it "points to the browser's window object (such as event handle events handler, etc.)--unless we change the pointer to this." The scope of many of the EXT classes is a configuration item (configuration) that is capable of binding the pointer. Related examples refer to ajax.request.
Ext's createdelegate function
* In addition to the built-in Call/apply method, Ext also provides us with--auxiliary method CreateDelegate. The basic function of this function is to bind the this pointer but not execute it immediately. Passing in a parameter, the CreateDelegate method guarantees that the function is running in the scope of this parameter. Such as:
Copy Code code as follows:

var obj = {
Tostring:function () {return ' obj ' within scope (scope) ';},//rewrite the ToString function to facilitate execution of the console.log (this) output
Func:function () {
The function here is directly subordinate to the object "objects"
Console.log (this);
var innerfunc = function () {
n the function here is not a direct member of a particular object, but a variable of another function.
Console.log (this);
};
Innerfunc = Innerfunc.createdelegate (this); Here we cover the original function with the function of the delegate.
Innerfunc (); Calling functions in the usual way
}
};
Obj.func ();
Output "within the scope of obj (in scope)"
Output "within the scope of obj (in scope)"

This is a small example, its principle is very basic foundation, hope to be able to digest well. Nevertheless, in the real work, we still easy to be confused, but basically, if can follow the above theoretical knowledge to analyze the ins and outs, change or not away from it.
Another thing to look at is the following example:
Copy Code code as follows:

Varsds.load ({callback:function (records) {
Col_length = Varsds.getcount ();//The vards here left the scope?
Col_length = This.getcount ()//This is equal to the store?
for (var x = 0; x < Col_length + +)
{
COLARRAY[X] = Varsds.getat (x). Get (' hex ');
}
}); But it can be written more clearly:
var obj = {
Callback:function (Records) {
Col_length = Varsds.getcount ();//The vards here left the scope?
Col_length = This.getcount ()//This is equal to the store?
// ...
}
};

Varsds.load (obj); The function callback now hangs directly on obj, so the this pointer equals obj.
But note: It's no use doing that. Why? Because you don't know what happens when Obj.callback finally executes. Imagine the Ext.data.Store load method (The imitation Implementation):
Copy Code code as follows:

...
Load:function (config) {
var o = {};
O.callback = Config.callback;
To load
O.callback ();
}
...

In this mock implementation, the callback function is scoped to the private variable "O". Because you don't usually know how a function is invoked, you probably won't be able to use the This parameter in a callback function if you don't declare the scope.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.