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

JavaScript anonymous function and closure_javascript skills

May 16, 2016 pm 06:01 PM
javascript anonymous function

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage and characteristics of C++ anonymous functions Usage and characteristics of C++ anonymous functions Apr 19, 2024 am 09:03 AM

An anonymous function, also known as a lambda expression, is a function that does not specify a name and is used for one-time use or to pass a function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Can Golang anonymous functions return multiple values? Can Golang anonymous functions return multiple values? Apr 13, 2024 pm 04:09 PM

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1,arg2,...,argN)(ret1,ret2,...,retM){//Function body}. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

Python Lambda expressions: abbreviated, concise, powerful Python Lambda expressions: abbreviated, concise, powerful Feb 19, 2024 pm 08:10 PM

pythonLambda expressions are a powerful and flexible tool for creating concise, readable, and easy-to-use code. They are great for quickly creating anonymous functions that can be passed as arguments to other functions or stored in variables. The basic syntax of a Lambda expression is as follows: lambdaarguments:expression For example, the following Lambda expression adds two numbers: lambdax,y:x+y This Lambda expression can be passed to another function as an argument as follows: defsum( x,y):returnx+yresult=sum(lambdax,y:x+y,1,2)In this example

Python Lambda Expressions: Making Programming Easier Python Lambda Expressions: Making Programming Easier Feb 19, 2024 pm 09:54 PM

A python Lambda expression is a small anonymous function that stores an expression in a variable and returns its value. Lambda expressions are often used to perform simple tasks that can be accomplished by writing a separate function, but Lambda expressions can make the code more concise and readable. The syntax of a Lambda expression is as follows: lambdaarguments: expressionarguments is the parameter list received by the Lambda expression, and expression is the body of the Lambda expression, which contains the code that needs to be executed. For example, the following Lambda expression adds two numbers and returns their sum: lambdax,

Python Lambda expressions: Uncovering the power of anonymous functions Python Lambda expressions: Uncovering the power of anonymous functions Feb 24, 2024 am 09:01 AM

Lambda expression in python is another syntax form of anonymous function. It is a small anonymous function that can be defined anywhere in the program. A lambda expression consists of a parameter list and an expression, which can be any valid Python expression. The syntax of a Lambda expression is as follows: lambdaargument_list:expression. For example, the following Lambda expression returns the sum of two numbers: lambdax,y:x+y. This Lambda expression can be passed to other functions, such as the map() function: numbers=[ 1,2,3,4,5]result=map(lambda

How to implement an online electronic signature system using WebSocket and JavaScript How to implement an online electronic signature system using WebSocket and JavaScript Dec 18, 2023 pm 03:09 PM

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online

See all articles