/**
* Scope of closures
*/
FN1 (); FN1 is able to execute without error, and for functions defined by the function func_name (), it will always be initialized first.
function fn1 () {
Console.log ("fn1");
}
FN2 (); Error: FN2 is not a function
/**
* Use the following method to define the function, will not be executed first, if called before the definition, error.
* This function is defined by first creating an area in memory and then pointing to the area with a fn2 variable.
* This area has no name at the beginning of the function, and the function name is called an anonymous function.
*/
var fn2 = function () {
Console.log ("fn2");
}
----------------------------------function Scope--------------------------------------
/**
* In JS, when a function call is made, an attribute scope is added to each function, which points to a piece of memory,
* This memory contains the variables used in the context, and when a new function is called in a function, the new function will still have
* A scope to point to the scope of the original function and its own newly added scope, thus forming a chain structure,
* This is the scope chain in JS.
*/
var color = "Red";
var showcolor = function () {
Console.log (This.color);
}
function ChangeColor () {
var anothercolor = "Blue";
function Swapcolor () {
var tempcolor = Anothercolor;
Anothercolor = color;
color = Tempcolor;
}
Swapcolor ();
}
ChangeColor ();
Showcolor (); Blue
To perform the steps:
Release Swapcolor
Release ChangeColor
Executive Showcolor
--------------------------------------------------------------------------
var name = "One";
var object = {
Name: "Both",
Getname:function () {
var name = "three";
return function () {
return this.name;
return name;
};
}
};
Console.log (Object.getname ()); One
What do you want to ask? What if you add a var name = "Three" in the GetName function? If the return this.name in the anonymous function; Change to return name; It?
What is the return value and why?
If you can understand the results of the above code, you should understand the operation mechanism of the closure.
/**
* The use of closures although the scope can be sung, but also occupy too much memory, generally not special cases do not use closures.
*
*/