search
HomeWeb Front-endJS TutorialAdvanced learning of JavaScript functions and detailed explanation of advanced function example codes

Anonymous functions and nested functions

In JavaScript, you can declare a function without a name, called an anonymous function (Anonymouse Function). At the same time, JavaScript also allows functions to be declared inside functions, called nested functions. The scope of a nested function is the entire parent function.

In the previous part of function declaration, we saw a use of anonymous functions and nested functions. Since anonymous functions have no names, they will not introduce new variables to pollute the context, and will bring new variable effects. domain, so anonymous functions are often used to prevent global environment pollution.

There is a special global environment (global object) in JavaScript runtime. This object stores global functions and variables. In actual development, several third-party libraries or multiple js files are often used. If not Be careful to introduce repeated variable or function declarations in the global object, which will cause confusion in code execution. For example, two js files are introduced one after another, and each defines its own function log for internal use. The second introduced function will overwrite the first definition and will not throw any errors. Calling the log function in subsequent executions may cause problems. causing errors. At this time, using an anonymous function to wrap the logic in the entire js can avoid this error. This method has been used by most open source js libraries.

(function() { // 匿名函数 
   
 function log(msg) { 
     console.log(msg); 
 } 
   
 // 其他代码 
   
 }()); // 立即执行

The above code is a simple example. The scope of the log function is limited to this anonymous function, and the anonymous function is surrounded by a pair of parentheses () to form a function expression. , the value of the expression is a function, followed by a pair of parentheses to indicate that the function will be executed immediately, allowing the original code to be executed normally. However, functions declared in this way, variables declared via var, etc. are internal and cannot be accessed by any code other than anonymous functions. If you need to expose some functions as interfaces, there are several methods as follows:

 var mylib = (function(global) { 
   
 function log(msg) { 
   console.log(msg); 
 } 
   
 log1 = log;  // 法一:利用没有var的变量声明的默认行为,在log1成为全局变量(不推荐) 
   
 global.log2 = log;  // 法二:直接在全局对象上添加log2属性,赋值为log函数(推荐) 
   
 return {  // 法三:通过匿名函数返回值得到一系列接口函数集合对象,赋值给全局变量mylib(推荐) 
    log: log
 }; 
   
 }(window));

High-order Function

If the function is used as a parameter or return value , is called a higher-order function. Functions in JavaScript can be used as higher-order functions. This is also a characteristic of the first type of function. Below we will analyze these two usage methods respectively.

 function negative(n) { 
   return -n; // 取n的相反值 
 } 
   
 function square(n) { 
   return n*n; // n的平方 
 } 
   
 function process(nums, callback) { 
   var result = []; 
   
   for(var i = 0, length = nums.length; i < length; i++) { 
     result[i] = callback(nums[i]); // 对数组nums中的所有元素传递给callback进行处理,将返回值作为结果保存 
   } 
   
   return result; 
 } 
   
 var nums = [-3, -2, -1, 0, 1, 2, 3, 4]; 
 var n_neg = process(nums, negative); 
 // n_neg = [3, 2, 1, 0, -1, -2, -3, -4]; 
 var n_square = process(nums, square); 
 // n_square = [9, 4, 1, 0, 1, 4, 9, 16];

The above code shows an example of passing a function as a parameter into another function process call. In the implementation of the process function, the callback is treated as a black box, responsible for passing the parameters to it, and then getting the return value, the specific implementation of the callback is not known before the call. Only when lines 20 and 22 are executed, the callback is represented by negative or square respectively, and the opposite or square value operation is performed on each element respectively.

 function generator() { 
   var i = 0; 
   return function() { 
     return i++; 
   }; 
 } 
   
 var gen1 = generator(); // 得到一个自然数生成器 
 var gen2 = generator(); // 得到另一个自然数生成器 
 var r1 = gen1(); // r1 = 0 
 var r2 = gen1(); // r2 = 1 
 var r3 = gen2(); // r3 = 0 
 var r4 = gen2(); // r4 = 1

The above code shows an example of using a function as a return value. generator is a natural number generator function, and the return value is a natural number generator function. Each time the generator is called, an anonymous function is returned as the result. This anonymous function returns each natural number in turn when it is actually called.

The above is the detailed content of Advanced learning of JavaScript functions and detailed explanation of advanced function example codes. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool