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 difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
