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.

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


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

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!
