JavaScript anonymous functions (anonymous function) and closures (closure) _javascript Tips

Source: Internet
Author: User
Tags closure function definition variable scope
The content of this article
Introduced
anonymous functions
Closed Bag
Variable scope
Local variables within the function's external access function
Implementing private members with closures
Introduced
Closures are implemented using anonymous functions. A closure is a protected variable space, generated by an inline function. The idea of "protecting variables" is seen in almost every programming language.
Look at the JavaScript scopes first:
JavaScript has a function-level scope. This means that variables that are defined inside a function cannot be accessed outside of a function.
The scope of JavaScript is lexical in nature (lexically scoped). This means that the function runs in the scope in which it is defined, not in the scope in which it is invoked. This is a major feature of JavaScript that will be explained later.
By combining these two factors, you can protect the variables by wrapping them in the anonymous function. You can create a private variable for a class like this:
Copy Code code as follows:

var Baz;
(function () {
var foo = 10;
var bar = 2;
Baz = function () {
return foo * BAR;
};
})();
Baz ();

Although executed outside the anonymous function, Baz still has access to Foo and bar.

Description

1, line 1th, Baz is a global variable;

2, 3rd ~ 9th line, define an anonymous function;

3, 4th and 5 lines, Foo and bar are local variables within the anonymous function, and the 6th ~ 8 line defines an anonymous function within the anonymous function and assigns it to the global variable Baz;

4, line 10th, call Baz. If changed to "alert (Baz ());", 20 will be displayed;

5, it stands to say, you can't access Foo and bar outside of anonymous functions, but you can now.

Before you explain the closure, understand the anonymous function first.



anonymous functions
Anonymous functions are those that do not have the function name defined. Anonymous functions are one thing with Lambda expressions (lambda expressions). The only difference--the grammatical form is different. The LAMBDA expression goes further. In essence, their function is to produce the method--inline method, that is, omit function definition, directly write function body.

Lambda expressions in general form:

(input parameters) => {statement;}
which

A list of arguments that can have multiple, one, or no parameters. Parameters can be implicitly or explicitly defined.
An expression or a statement block, or a function body.
The above code, 6th ~ 8 lines, no function name, is an anonymous function, using LAMBDA expression, in strict sense, although the syntax is different, but the same purpose.

Example 1:
Copy Code code as follows:

var baz1 = function () {
var foo = 10;
var bar = 2;
return foo * BAR;
};
function Mutil () {
var foo = 10;
var bar = 2;
return foo * BAR;
};
Alert (BAZ1 ());
var baz2 = Mutil ();
alert (BAZ2);

Description

1,BAZ1 is exactly the same as BAZ2, but BAZ1 does not have the function definition, the direct function body--looks more simple than baz2.



Closed Bag
Variable scope
Example 2: Global variables can be accessed within functions.

Copy Code code as follows:

var baz = 10;
function foo () {
alert (BAZ);
}
Foo ();


It is possible.

Example 3: Local variables inside a function cannot be accessed outside of a function.

Copy Code code as follows:

function foo () {
var bar = 20;
}
alert (bar);


This will be an error.

In addition, when declaring a variable inside a function, be sure to use the var keyword, otherwise, declare a global variable.

Example 4:

Copy Code code as follows:

function foo () {
bar = 20;
}
alert (bar);


Local variables within the function's external access function
In fact, we need to get the local variables inside the function from outside the function. See Example 5 first.

Example 5:

Copy Code code as follows:

function foo () {
var a = 10;
function Bar () {
A *= 2;
}
Bar ();
return A;
}
var baz = foo ();
alert (BAZ);


A is defined within Foo, bar is accessible because bar is also defined in Foo. Now, how do I get bar to be called Outside of Foo?

Example 6:

Copy Code code as follows:

function foo () {
var a = 10;
function Bar () {
A *= 2;
return A;
}
return bar;
}
var baz = foo ();
Alert (Baz ());
Alert (Baz ());
Alert (Baz ());

var blat = foo ();
Alert (Blat ());


Description

1, you can now access a from the outside;

The scope of the 2,javascript is lexical in nature. A is running in the Foo that defines it, rather than running in the scope of calling Foo. As long as bar is defined in Foo, it can access the variable a defined in Foo, even if Foo's execution has ended. That is to say, after the "var baz = foo ()" is executed, Foo has finished executing, a should not exist, but then the call to Baz found that a still exists. This is one of the JavaScript features-running calls that are defined rather than run.

where "var baz = foo ()" is a reference to a bar function; "Var blat= foo ()" is another bar function reference.

Implementing private members with closures
Now you need to create a variable that can only be accessed inside the object. A closure is a good fit, because by closures you can create variables that allow only certain functions to be accessed, and those variables remain between invocations of these functions.

To create a private property, you need to define the relevant variable in the scope of the constructor. These variables can be defined for all function accesses in the scope, including those of the privileged methods.

Example 7:

Copy Code code as follows:

var book = function (NEWISBN, Newtitle, Newauthor) {
Private property
var ISBN, title, author;
Private method
Function Checkisbn (ISBN) {
Todo
}
Privileged methods
THIS.GETISBN = function () {
return ISBN;
};
THIS.SETISBN = function (NEWISBN) {
if (!CHECKISBN (NEWISBN)) throw new Error (' Book:invalid ISBN. ');
ISBN = NEWISBN;
};
This.gettitle = function () {
return title;
};
This.settitle = function (newtitle) {
title = Newtitle | | ' No title specified. '
};
This.getauthor = function () {
return author;
};
This.setauthor = function (Newauthor) {
Author = Newauthor | | ' No author specified. '
};
Builder code
THIS.SETISBN (NEWISBN);
This.settitle (Newtitle);
This.setauthor (Newauthor);
};

Shared, non-privileged methods
Book.prototype = {
Display:function () {
Todo
}
};


Description

1, declaring variables ISBN, title, and author in Var, instead of this, means that they exist only in the book Builder. The CHECKISBN function is also because they are private;

2, the way to access private variables and methods is simply to declare them in the book. These methods are called privileged methods. Because they are public methods, they can access both private and private methods, such as GETISBN, SETISBN, GetTitle, Settitle, Getauthor, Setauthor (accessors, and constructors).

3, these methods are added to the This keyword in order to be able to access these privileged methods outside the object. Because these methods are defined in the scope of the book constructor, they are able to access the private variables ISBN, title, and author. However, when referencing ISBN, title, and author variables in these privileged methods, the This keyword is not used, but is referenced directly. Because they are not public.

4, any method that does not require direct access to the private variable, as stated in Book.prototype, such as display. It does not require direct access to private variables, but rather through get*, set* profile access.

5, the object created in this way can have a truly private variable. Other people cannot directly access any of the book object's internal data, only through the assignment and. It's all under control.

But the disadvantage of this approach is:

Portal large open object creation mode, all methods are created in the prototype prototype object, so there is only one copy of the methods in memory, regardless of how many object instances are generated.
In the practice of this section, no new object instance is generated, and each private method (e.g., CHECKISBN) and privileged methods (such as GETISBN, SETISBN, GetTitle, Settitle, Getauthor, Setauthor) to generate a new copy.
Therefore, this section method is only suitable for situations where private members are really needed. In addition, this approach is not conducive to inheritance.

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.