JavaScript anonymous function and closure_javascript skills
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:
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:
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.
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.
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:
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:
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:
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:
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.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment