Home >Web Front-end >JS Tutorial >JavaScript anonymous function and closure_javascript skills

JavaScript anonymous function and closure_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:01:171273browse

Contents of this article
Introduction of
anonymous function
Closure
Variable scope
Accessing local variables inside the function from outside the function
Using closures to implement private members
Introduction of
closure Packages are implemented using anonymous functions. A closure is a protected variable space generated by an embedded function. The idea of ​​"protected variables" can be seen in almost all programming languages.
Let’s take a look at JavaScript scope first:
JavaScript has function-level scope. This means that variables defined inside a function cannot be accessed from outside the function.
The scope of JavaScript is lexically scoped. This means that the function runs in the scope in which it is defined, not in the scope in which it is called. This is a major feature of JavaScript, which will be explained later.
Putting these two factors together, you can protect variables by wrapping them in anonymous functions. You can create private variables of a class like this:

Copy the code The code is as follows:

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

Despite executing outside the anonymous function, baz still has access to foo and bar.

Explanation:

1, line 1, baz is a global variable;

2, lines 3 to 9, define an anonymous function;

3, lines 4 and 5, foo and bar are local variables within the anonymous function; lines 6 to 8, define an anonymous function within the anonymous function and assign it to the global variable baz;

4, Line 10, calls baz. If changed to "alert(baz());", 20 will be displayed;

5. Logically speaking, foo and bar cannot be accessed outside anonymous functions, but now they can.

Before explaining closures, let’s first understand anonymous functions.



Anonymous functions
Anonymous functions are those functions that do not need to define a function name. Anonymous functions are the same thing as lambda expressions. The only difference is the grammatical form. Lambda expressions go one step further. In essence, their function is to generate methods - inline methods, that is to say, omit the function definition and write the function body directly.

Lambda expression general form:

(input parameters) => {statement;}
where:

Parameter list, there can be multiple, one or No parameters. Parameters can be defined implicitly or explicitly.
Expression or statement block, which is the function body.
The above code, lines 6 to 8, has no function name and is an anonymous function using Lambda expression. Strictly speaking, although the syntax is different, the purpose is the same.

Example 1:
Copy code The code is 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);

Explanation:

1, baz1 is exactly the same as baz2, but compared with baz2, baz1 omits the function definition and directly uses the function body - it looks so simple.



Closure
Variable scope
Example 2: Global variables can be accessed inside the function.

Copy code The code is as follows:

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


This is OK.

Example 3: Local variables inside the function cannot be accessed from outside the function.

Copy code The code is as follows:

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


This will report an error.

In addition, when declaring variables inside a function, you must use the var keyword, otherwise, a global variable is declared.

Example 4:

Copy code The code is as follows:

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


Access local variables inside the function from outside the function
Actual situation, We need to obtain the local variables inside the function from outside the function. Let’s look at example 5 first.

Example 5:

Copy code The code is as follows:

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


a is defined in foo, bar can be accessed because bar is also defined within foo. Now, how do I get bar to be called outside of foo?

Example 6:

Copy code The code is 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());


Note:

1, a can now be accessed from the outside;

2, JavaScript The scope of is lexical. a runs in foo in which it is defined, not in the scope in which foo is called. As long as bar is defined in foo, it can access the variable a defined in foo, even if the execution of foo has ended. In other words, it stands to reason that after "var baz = foo()" is executed, foo has been executed and a should no longer exist. However, when baz is called later, it is found that a still exists. This is one of the characteristics of JavaScript - running on definitions, not running calls.

Among them, "var baz = foo()" is a reference to a bar function; "var blat= foo()" is a reference to another bar function.

Use closures to implement private members
Now, you need to create a variable that can only be accessed inside the object. Closures are perfect because they allow you to create variables that only certain functions can access, and they persist across calls to those functions.

In order to create a private property, you need to define the relevant variable in the scope of the constructor. These variables can be accessed by all functions defined in the scope, including those by privileged methods.

Example 7:

Copy code The code is as follows:

var Book = function(newIsbn, newTitle, newAuthor) {
// Private property
var isbn, title, author;
// Private method
function checkIsbn(isbn) {
// TODO
}
// Privileged method
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.';
};
//Constructor code
this.setIsbn(newIsbn);
this.setTitle(newTitle);
this.setAuthor(newAuthor);
};

// Public, non-privileged method
Book .prototype = {
display: function() {
// TODO
}
};


Description:

1, Declaring the variables isbn, title, and author with var instead of this means that they only exist in the Book constructor. The same goes for the checkIsbn function, because they are private;

2. The methods to access private variables and methods only need to be declared in Book. These methods are called privileged methods. Because they are public methods, but they can access private variables and private methods, like getIsbn, setIsbn, getTitle, setTitle, getAuthor, setAuthor (value getters and constructors).

3. In order to access these privileged methods outside the object, the this keyword is added in front of these methods. Because these methods are defined in the scope of the Book constructor, they have access to the private variables isbn, title, and author. But when referencing isbn, title and author variables in these privileged methods, the this keyword is not used, but is quoted directly. Because they are not public.

4. Any method that does not require direct access to private variables, such as those declared in Book.prototype, such as display. It does not need to access private variables directly, but through get*, set* introduction.

5, objects created in this way can have truly private variables. Others cannot access any of the Book object's internal data directly, only through the evaluator. This way you have everything under control.

But the disadvantage of this approach is:

In the "open door" object creation mode, all methods are created in the prototype prototype object, so no matter how many object instances are generated, these methods There is only one copy in memory.
With the approach of this section, if a new object instance is not generated, one will be generated for each private method (such as checkIsbn) and privileged method (such as getIsbn, setIsbn, getTitle, setTitle, getAuthor, setAuthor) New copy.
Therefore, the method in this section is only suitable for use in situations where private members are really needed. In addition, this approach is not conducive to inheritance.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn