JS anonymous functions and Closures (javascript Advanced programming 3rd Edition)

Source: Internet
Author: User
Tags closure

A anonymous Functions

Common Functions

function box () {// functions name is box

Return ' Lee ';

}

Anonymous Functions

function () {// anonymous functions, error

Return ' Lee ';

}

self-executing with an expression

(function box () {// encapsulated as an expression

Alert (' Lee ');

})(); () represents the execution function, and the argument

assigning anonymous functions to variables

var box = function () {// assign anonymous function to variable

Return ' Lee ';

};

Alert (box ()); similar to call methods and function calls

anonymous functions in a function

function Box () {

return function () {/// function anonymous functions, resulting in closures

Return ' Lee ';

}

}

Alert (box () ()); Calling anonymous functions

Two Closed Package

Closures are functions that have access to variables in another function scope, and the common way to create closures is to create another function inside one function and access the local variables of the function through another Function.

you can return a local variable by closing a packet

function Box () {

var user = ' Lee ';

return function () {//return box () local variable via anonymous function

Return user;

};

}

Alert (box () ()); direct call to anonymous function return value via box () ( )

var b = Box ();

Alert (b ()); Another call to the anonymous function returns a value

the use of closures has one advantage, but also its disadvantage: it is possible to put local variables in memory, you can avoid the use of global variables. ( global variable pollution causes application unpredictability, and each module can invoke a disaster, so it is recommended to use a private, encapsulated local variable ).

to accumulate by global variables

var age = 100; Global Variables

function Box () {

Age + +; the module level can call global variables and accumulate

}

Box (); Execute function, accumulate

Alert (age); Output Global Variables

accumulation cannot be achieved by local variables

function Box () {

var age = 100;

Age + +; Accumulate

Return age;

}

Alert (box ()); 101

Alert (box ()); 101, unable to implement because it was initialized again

the accumulation of local variables can be realized by closures

function Box () {

var age = 100;

return function () {

Age + +;

Return age;

}

}

var b = Box (); Get function

Alert (b ()); Calling anonymous functions

Alert (b ()); the second call to the anonymous function implements the cumulative

PS: Because the local variable returned by the scope in the closure is not destroyed immediately, it may consume more memory. Excessive use of closures can result in degraded performance, and it is recommended that closures be used when necessary.

The mechanism of the scope chain causes a problem in which any variable obtained by an anonymous function in the loop is the last Value.

an anonymous function is included in the loop

function Box () {

var arr = [];

for (var i = 0; i < 5; i++) {

arr[i] = function () {

Return i;

};

}

Return arr;

}

var b = Box (); get an array of functions

Alert (b.length); get the function set length

for (var i = 0; i < b.length; i++) {

Alert (b[i] ()); output The value of each function, which is the last value

}

the above example outputs a result of 5, which is the maximum I valueobtained after the loop . Because b[i] calls an anonymous function, the anonymous function is not self-executing, and when the callis made,box () is executed,i have already become 5 , so the end result is 5 a 5 .

the loop contains anonymous functions - change 1, self-executing anonymous functions

function Box () {

var arr = [];

for (var i = 0; i < 5; i++) {

arr[i] = (function (num) {// self-executing

Return num;

}) (i); and to pass the argument

}

Return arr;

}

var b = Box ();

for (var i = 0; i < b.length; i++) {

Alert (b[i]); This returns an array, which can be printed directly .

}

in 1 , we let the anonymous function execute itself, resulting in an array instead of a function that ultimately returns to a[i] . The value of 0,1,2,3,4 is retained in the resulting b[0]-b[4] .

The loop contains an anonymous function - change 2, anonymous function, and then do an anonymous function

function Box () {

var arr = [];

for (var i = 0; i < 5; i++) {

arr[i] = (function (num) {

return function () {// direct return value, change 2 to return

Return num; principle and change 1 as

}

}) (i);

}

Return arr;

}

var b = Box ();

for (var i = 0; i < b.length; i++) {

Alert (b[i] ()); This is done through the b[i] () function call .

}

in 1 and 2 , we execute it by anonymous function and immediately assign the result to a[i]. Each i, is the caller passed by value, so the final return is the specified increment of i. instead of Iin the box () function .

about This object

The use of this object in closures can also cause some problemswhen the this object is bound at run time based on the execution environment of the function, if this is in the global scope window, which points to the object if it is inside the Object. closures, however, point to window at run time , because closures do not belong to properties or methods of this Object.

var user = ' The Window ';

var obj = {

User: ' The Object ',

Getuserfunction:function () {

return function () {// closures are not part of obj, This is pointing to window

Return this.user;

};

}

};

Alert (obj.getuserfunction () ()); The window

can force point to an object

Alert (obj.getuserfunction (). Call (obj)); The Object

You can also get objects from the previous scope

Getuserfunction:function () {

var = this; object from the Object's method

return function () {

Return that.user;

};

}

Memory leaks

because The JScript objects and DOM objects of IE use different garbage collection methods, so closures can cause problems in Ie. Is the problem of memory leaks, which means that elements residing in memory cannot be destroyed. The following code has two knowledge points that have not been learned, one is DOM, the other is an Event.

function Box () {

var odiv = document.getElementById (' odiv '); Odiv has been in memory since it was run out

Odiv.onclick = function () {

Alert (odiv.innerhtml); The memory leaks are caused by odiv here.

};

}

Box ();

then the odiv should be dereferenced at the end to avoid a memory Leak.

function Box () {

var odiv = document.getElementById (' odiv ');

var text = odiv.innerhtml;

Odiv.onclick = function () {

Alert (text);

};

Odiv = null; de-referencing

}

PS: If you do not use dereference, you need to wait until the browser is closed to Release.

Mimic Block-level Scopes

JavaScript does not have the concept of block-scoped Scopes.

function Box (count) {

For (var i=0; i<count; i++) {}

Alert (i); I will not expire because I left the for block

}

Box (2);

function Box (count) {

For (var i=0; i<count; i++) {}

var i; even if you re-declare it, it won't be the previous value

Alert (i);

}

Box (2);

The above two examples illustrate JavaScript does not have a scope for block-level statements,and if() {} for () {} is not scoped, if so, the range i should be Destroyed. Even if you re-declare the same variable, it will not change its value.

JavaScript does not remind you that you have declared the same variable more than once; in this case, it will only turn a blind eye to the subsequent declarations ( if initialized, of course ). Using the impersonation Block-level scope avoids this problem.

Impersonation Block-level Scope ( private scope )

(function () {

This is a block level scope .

})();

overwrite with block-level scope ( private scope )

function Box (count) {

(function () {

for (var i = 0; i<count; i++) {}

})();

Alert (i); error, Unable to access

}

Box (2);

block-level scopes are used ( private Scope ) , any variables defined in the anonymous function will be destroyed at the end of Execution. This technique is often used outside the function in the global scope to limit the addition of too many variables and functions to the global scope. In general, we should add variables and functions to the global scope as little as Possible. In large projects, when Multi-person development, too many global variables and functions can easily lead to naming conflicts, causing catastrophic consequences. With Block-level scopes ( private scopes ), each developer can use his or her own variables without worrying about messing up the global scope.

(function () {

var box = [1,2,3,4];

Alert (box); Box came out, and I don't know.

})();

Using a block-level scope in a global scope reduces the memory problems that are used by closures because there is no reference to the anonymous Function. As soon as the function is executed, its scope chain can be destroyed immediately.

Private variables

JavaScript does not have the concept of private properties; all object properties are Public. however, There is a concept of a private variable. Any variable defined in a function can be considered a private variable, because these variables cannot be accessed outside of the Function.

function Box () {

var age = 100; Private variable, External unreachable

}

By creating a closure within the function, the closures can also access these variables through their own scope chain. With this, you can create a public method that accesses a private variable.

function Box () {

var age = 100; Private Variables

function Run () {// private Functions

Return ' running ... ';

}

This.get = function () {// External public Privileged method

Return age + Run ();

};

}

var box = new Box ();

Alert (box.get ());

You can access a private variable by constructing a method pass Parameter.

function Person (value) {

var user = value; This sentence can actually be omitted

This.getuser = function () {

Return user;

};

This.setuser = function (value) {

user = value;

};

}

however, the method of an object is created multiple times when it is called multiple Times. You can use static private variables to avoid this problem.

Static private variables

through Block-level scopes ( private Scope ) defines a private variable or function, you can also create an external public privileged Method.

(function () {

var age = 100;

Function Run () {

Return ' running ... ';

}

Box = function () {}; Construction Method

Box.prototype.go = function () {// prototype method

Return age + Run ();

};

})();

var box = new Box ();

Alert (box.go ());

the above object declaration, using the box = function () {} instead of function Box () {} because if you use the latter, it becomes a private function and cannot be accessed globally, so we use the Preceding.

(function () {

var user = ';

person = function (value) {

user = value;

};

Person.prototype.getUser = function () {

Return user;

};

Person.prototype.setUser = function (value) {

user = value;

}

})();

using prototype causes the method to be shared, and the user becomes a static Property. ( the so-called static property, which is a property shared in a different object ).

Module mode

previously, The constructor was used to create private variables and privileged METHODS. Then the object literal is created using module Mode.

var box = {// literal object, also singleton object

age:100,// This is a public attribute and will be changed to private

Run:function () {/// at this time the public function will be changed to private

Return ' running ... ';

};

};

Privatization variables and Functions:

var box = function () {

var age = 100;

Function Run () {

Return ' running ... ';

}

Return {// returns object directly

Go:function () {

Return age + Run ();

}

};

}();

The above example of a direct return object can also be written like this:

var box = function () {

var age = 100;

Function Run () {

Return ' running ... ';

}

var obj = {// Create literal object

Go:function () {

Return age + Run ();

}

};

Return obj; return This object

}();

The literal object declaration, in fact, can be regarded as a singleton pattern in the design pattern, so-called singleton mode, which is always an instance of preserving the Object.

Enhanced module mode, which is suitable for returning custom objects, that is, Constructors.

function Desk () {};

var box = function () {

var age = 100;

Function Run () {

Return ' running ... ';

}

var desk = new Desk (); you can instantiate a specific object

Desk.go = function () {

Return age + Run ();

};

Return desk;

}();

Alert (box.go ());

JS anonymous functions and Closures (javascript Advanced programming 3rd Edition)

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.