Home Web Front-end HTML Tutorial JavaScript function expressions

JavaScript function expressions

Nov 04, 2016 pm 05:00 PM
javascript function expression

Define function: a. Function declaration function functionName (name, age) {}————Function declaration promotion

                                      b. Function expression var functionName=function (name, age) {};

Recursion

Closure

The scope of variables is nothing more than two types: global variables and local variables.

The special thing about Javascript language is that global variables can be read directly inside the function.

How to read local variables from outside?

That is to define another function inside the function. By using the internal function as the return value, you can read its internal variables from the outside. A closure is a function that can read the internal variables of other functions.

Since in the Javascript language, only sub-functions inside the function can read local variables, closures can be simply understood as "functions defined inside a function".

So, in essence, closure is a bridge connecting the inside of a function with the outside of the function.

It has two biggest uses. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values ​​of these variables in memory.

Notes on using closures

1) Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page. May cause memory leak in IE. The solution is to delete all unused local variables before exiting the function.

2) Closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.

Closure is a relatively abstract concept, especially for js novices. The explanation in the book is really obscure, and it is the same for me.

But it is also something that cannot be bypassed in improving js capabilities. The first step is a question that must be asked in almost every interview, because when you answer it, the depth of your answer, your understanding of terminology, and the description of the operation of the internal interpreter of js can all reveal your actual js level. Even if you don’t answer correctly, you can let the examiner evaluate your level. So let me first talk about my understanding of closures in js.

Closures are a feature that many languages ​​have. In js, closures Packages mainly involve several other features of js: scope chain, garbage (memory) recycling mechanism, function nesting, etc.

Before understanding closures, it is best to understand the meaning of scope chain first. To put it simply, the scope chain is an index created when the function is defined to find the value of the variable used. Its internal rule is to put the local variables of the function itself at the front and its own The variables in the parent function are placed second, and the variables in the higher-level function are placed further behind, and so on until the global object. When the value of a variable needs to be queried in the function, the js interpreter will take action Search the domain chain, starting with the local variable at the front. If the corresponding variable is not found, go to the next level of the chain. Once the variable is found, it will not continue. If you find the variable you need, you will not find it at the end. variable, the interpreter returns undefined.

After understanding the scope chain, let’s take a look at the memory recycling mechanism of js. Generally speaking, when a function starts executing, the variables defined in it will be divided into memory spaces to save them. They are used for subsequent statements. When the function completes execution and returns, these variables are considered useless. The corresponding memory space is also reclaimed. The next time this function is executed, all variables return to their original values. Status, reassigned. But if there is another function nested inside this function, and this function may be called externally. And this internal function uses some variables of the external function. This kind of memory There will be problems with the recycling mechanism. If the internal function is called directly after the external function returns, then the internal function will not be able to read the value of the variable in the external function that it needs. Therefore, the js interpreter encounters the function definition time, the function will be automatically saved together with the variables it may use (including local variables and variables (free variables) of parent and ancestor functions). That is to say, a closure will be constructed, and these variables will not be used by the memory collector. By recycling, the closure will be destroyed only when the internal function cannot be called (for example, it is deleted, or there is no pointer), and no variables referenced by the closure will be destroyed when the next memory recycling is started. Recycled.

In other words, with closures, nested function structures can operate, which is in line with our expectations. Then, closures have some features, but they are often difficult for programmers to understand.

Look at the code below.

var result=[];function foo(){
    var i= 0;
    for (;i<3;i=i+1){
        result[i]=function(){
            alert(i)
        }
    }
};
foo();
result[0](); // 3
result[1](); // 3
result[2](); // 3
Copy after login

这段代码中,程序员希望foo函数中的变量i被内部循环的函数使用,并且能分别获得他们的索引,而实际上,只能获得该变量最后保留的值,也就是说.闭包中所记录的自由变量,只是对这个变量的一个引用,而非变量的值,当这个变量被改变了,闭包里获取到的变量值,也会被改变.

解决的方法之一,是让内部函数在循环创建的时候立即执行,并且捕捉当前的索引值,然后记录在自己的一个本地变量里.然后利用返回函数的方法,重写内部函数,让下一次调用的时候,返回本地变量的值,改进后的代码

var result=[];function foo(){
    var i= 0;
    for (;i<3;i=i+1){
        result[i]=(function(j){
            return function(){
                alert(j);
            };
        })(i);
    }
};
foo();
result[0](); // 0
result[1](); // 1
result[2](); // 2
Copy after login

 

在这里我再解释一下.这里用到了另外2个技术,立即调用的匿名函数和返回函数.也是初学者比较难以理解的部分.

私有变量

任何在函数中定义的变量,都可以是私有变量。

把有权访问私有变量和私有函数的方法称为特权方法,a)在构造函数中定义特权方法

b)在私有作用域中定义变量或函数,私有变量和函数由实例共享

模块模式——为单例创建私有变量和特权方法。单例,指只有一个实例的对象

使用一个返回对象的匿名函数,函数内部首先定义私有变量和函数,将一个对象字面量作为函数的值返回,返回的 对象字面量只包含公开的属性和方法。


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

Video Face Swap

Video Face Swap

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

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)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles