Function
Closed Package
Presentation format
Principles of nested functions
Information hiding through closures
This section is mainly about function class and closure of the heavy difficulties.
Function
var obj= function();var sum = Function (‘a‘,‘b‘,‘return (a+b);‘);
function f() {}f.foo = ‘FOO‘;f.doit = function() { print(‘doit called‘);}}
The relationship of each part
Closed Package
Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.
Presentation format
function f() { var cnt =0;return g; function g() {return ++cnt;}}//也可以是function f() { var cnt =0; return function() {return ++cnt;}}
fn = f();print(fn());print(fn());print(fn());// 1// 2// 3
Principles of nested functions
- The precondition of closure is to declare another function inside the function declaration (that is, a nested function declaration).
- In JS, the call object is implicitly generated when the function is called, and when the function finishes, it destroys the calling object.
- Scope chain: For nested declared functions, the internal function will first look up the call object properties that were generated when called, and then look for the properties of the calling object for the outer function.
function f() { var n=123; function g() { print(n); } return g;}fn();var fn =f();//123//[Function: g]
The relationships between the various parts:
Information hiding through closures
- Format
//( {function() {函数体}} )();var sum = (function f() { var n=123; function g() { print(n); } return g;})();sum();//123
<wiz_tmp_tag id= "Wiz-table-range-border" contenteditable= "false" style= "Display:none;" >
From for notes (Wiz)
JavaScript Learning Notes