Javascript closures and javascript
Description of closures
We describe the scope chain as an object list, not a bound stack. Each time a javascript function is called, a new object is created for it to save the variable, and the object is added to the scope. When the function returns, delete the object bound to the variable from the scope chain. If no nested function exists and no other reference points to the bound object, it will be reclaimed as garbage,
(Function () {var val = null; var callback; setTimeout (function () {val = 1; callback (val) }, 1000) window. getVal = function (fn) {callback = fn ;}) (); (function () {var B = 3; getVal (function (val) {console. log (val); // 1 console. log (B); // 3 getVal (function (val) {console. log (val); console. log (B); // Why can I print the variable B /.}); // here the anonymous function is actually a closure. you can pass this closure through the getVal function. Do you think about it ?}) (); // 2 Scope (function () {var B = 3; var ret = function (val) {console. log (val );
Private Attribute access method implemented using closures
Function c return {count: function () {return n ++ ;};}var a = counter (); alert (. count (); // return 0; alert (. count (); // return 1;
Private Attribute method implemented by the defined Closure
Function addPrivateProperty (o, name, predicate) {var value; o ["get" + name] = function () {return value);} // get accessors read-only, directly return the // setter method to check whether the value is valid. If the value is invalid, an exception is thrown. o ["set" + name] = function (v) {if (predicate &&! Predicate (v) throw Error (""); else {value = v ;}}
Typical errors
Function constfuncs () {var funcs = []; for (var I = 0; I <10; I ++) {funcs [I] = function () {return I ;}}return funcs;} var func = constfuncs (); console. log (func [5] (); // return value? 10
Since the closure of this function is defined in the same function call, you can share variable I;
The scope chain associated with the closure is active. nested functions do not copy Private Members in the scope or generate static snapshots of the bound variables; after the closure, this is a javascript keyword instead of a variable.
Solution
Function Bb () {this. run = function () {}// this is the Bb object;} and function run () {function gg () {alert (this is the window)} // this is the window; '}
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!