Table of Contents
1. What is an anonymous function?
2. The difference between function literals and Function() constructors
3. Code pattern of anonymous functions
4. Application of anonymous functions
Home Web Front-end JS Tutorial Summary of anonymous functions in Javascript_javascript skills

Summary of anonymous functions in Javascript_javascript skills

May 16, 2016 pm 06:37 PM
javascript anonymous function

1. What is an anonymous function?

There are generally three ways to define a function in Javascript:

  1. Function keyword (function) statement:
    <code>function fnMethodName(x){alert(x);}</code>
    Copy after login
  2. Function Literals:
    <code>var fnMethodName = function(x){alert(x);}</code>
    Copy after login
  3. Function() constructor:
    <code>var fnMethodName = new Function('x','alert(x);')</code>
    Copy after login

The above three methods define the same method function fnMethodName. The first method is the most commonly used method. The latter two copy a function to the variable fnMethodName, and this function has no name, that is, an anonymous function. In fact, quite a few languages ​​have anonymous functions .

2. The difference between function literals and Function() constructors

  1. Although the function literal is an anonymous function, the syntax allows you to specify any function name for it. It can call itself when writing a recursive function, but not using the Function() constructor.
    <code>var f = function fact(x) {
     if (x < = 1) return 1;
     else return x*fact(x-1);
    };</code>
    Copy after login
  2. The Function() constructor allows dynamic creation and compilation of Javascript code at runtime. In this way it is similar to the global function eval().
  3. The Function() constructor parses the function body and creates a new function object each time it is executed. Therefore, the efficiency of calling the Function() constructor in a loop or frequently executed function is very low. In contrast, function literals are not recompiled every time they are encountered.
  4. When creating a function using the Function() constructor, it does not follow the typical scope. It always executes it as a top-level function.
    <code>var y = "global";
    function constructFunction() {
      var y = "local";
      return new Function("return y"); <span>// 无法获取局部变量</span>
    }
    alert(constructFunction()()); <span>// 输出 "global"</span>
    </code>
    Copy after login

Compared with function keyword definition, the Function() constructor has its own characteristics and is much more difficult to use, so this technology is usually rarely used. The function literal expression is very close to the function keyword definition. Considering the previous difference, although there is news that literal anonymous functions have bugs in some webkit engines under OS X 10.4.3, the anonymous functions we usually refer to refer to anonymous functions in the form of function literals. For more details, you can read the Functions chapter of "JavaScript: The Definitive Guide, 5th Edition".

3. Code pattern of anonymous functions

Yesterdayhedger wang introduced several anonymous function code patterns on his blog:

Error mode: It won’t work and the browser will report a syntax error.

<code>function(){
 alert(1);
}();</code>
Copy after login
  1. Function literal: First declare a function object and then execute it.
    <code>(function(){
     alert(1);
    } ) ( );</code>
    Copy after login
  2. Priority expression: Since Javascript executes expressions from the inside to the outside of the parentheses, you can use parentheses to force the execution of the declared function.
    <code>( function(){
     alert(2);
    } ( ) );</code>
    Copy after login
  3. Void operator : Use the void operator to perform a single operand not surrounded by parentheses.
    <code>void function(){
     alert(3);
    }()</code>
    Copy after login

These three methods are equivalent. Hedge Wang prefers the third method due to personal reasons, but in practical applications, what I have seen and used is the first method.

4. Application of anonymous functions

  1. The first sentence in "A Module Pattern for Javascript" is "Global variables are the devil". Combined with the var keyword, anonymous functions can effectively ensure that Javascript is written on the page without causing pollution to global variables. This is very effective and elegant when adding Javascript to an unfamiliar page. In fact, anonymous functions are widely used in YUI and its corresponding examples, and are also widely used in other Javascript libraries.
  2. Javascript is the cornerstone of functional programming. For details, please see "Writing Beautiful JavaScript with Functional Programming Techniques" and "Functional JavaScript Programming Guide" .
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Usage and characteristics of C++ anonymous functions Usage and characteristics of C++ anonymous functions Apr 19, 2024 am 09:03 AM

An anonymous function, also known as a lambda expression, is a function that does not specify a name and is used for one-time use or to pass a function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Can Golang anonymous functions return multiple values? Can Golang anonymous functions return multiple values? Apr 13, 2024 pm 04:09 PM

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1,arg2,...,argN)(ret1,ret2,...,retM){//Function body}. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

Python Lambda Expressions: Making Programming Easier Python Lambda Expressions: Making Programming Easier Feb 19, 2024 pm 09:54 PM

A python Lambda expression is a small anonymous function that stores an expression in a variable and returns its value. Lambda expressions are often used to perform simple tasks that can be accomplished by writing a separate function, but Lambda expressions can make the code more concise and readable. The syntax of a Lambda expression is as follows: lambdaarguments: expressionarguments is the parameter list received by the Lambda expression, and expression is the body of the Lambda expression, which contains the code that needs to be executed. For example, the following Lambda expression adds two numbers and returns their sum: lambdax,

What is the difference between lambda expressions and anonymous functions? What is the difference between lambda expressions and anonymous functions? Apr 17, 2024 pm 03:18 PM

Lambda expressions and anonymous functions are both ways of creating anonymous functions in Python, but there are differences. Assignment method: lambda expression returns a function, and anonymous functions must be assigned to variables to be used. Code complexity: A lambda expression can only contain one expression, while an anonymous function can contain multiple statements.

Python Lambda expressions: abbreviated, concise, powerful Python Lambda expressions: abbreviated, concise, powerful Feb 19, 2024 pm 08:10 PM

pythonLambda expressions are a powerful and flexible tool for creating concise, readable, and easy-to-use code. They are great for quickly creating anonymous functions that can be passed as arguments to other functions or stored in variables. The basic syntax of a Lambda expression is as follows: lambdaarguments:expression For example, the following Lambda expression adds two numbers: lambdax,y:x+y This Lambda expression can be passed to another function as an argument as follows: defsum( x,y):returnx+yresult=sum(lambdax,y:x+y,1,2)In this example

See all articles