Home Web Front-end JS Tutorial JavaScript function expressions (graphic tutorial)

JavaScript function expressions (graphic tutorial)

May 19, 2018 am 10:52 AM
javascript js expression

This article mainly introduces the detailed explanation and examples of JavaScript function expressions. Friends who need it can refer to

JavaScript function expressions

1. Preface

There are two ways to define a function: one is a function declaration, and the other is a function expression;

1.1 Function declaration

function functionName(arg){
   //函数体
}
Copy after login

Regarding function declaration, one of its important features is function declaration promotion, which means that the function declaration will be read before executing the code. This means that the function can be placed after the statement that calls it. As shown below:

helloworld(); //在代码执行之前会先读取函数声明
function helloworld(){
  console.log("hello world");
}
Copy after login

1.2 Function expression

var functionName=function(arg){
   //函数体
}
Copy after login

This form looks like It looks like a regular variable assignment statement, that is, creating a function and assigning it to the variable functionName. The function created in this case is called an anonymous function. Because there is no identifier after the function keyword.

Function expressions, like other expressions, must be assigned a value before use; the following code will cause an error;

helloworld(); //错误,还未赋值,函数不存在

var helloworld=function(){
  console.log("hello world");
}
Copy after login

There With the function expression, we can dynamically assign values ​​to the function expression; as shown in the following code:

var helloworld; //声明
if(condition){ //条件
  helloworld=function(){ //赋值
    console.log("hello world"); 
  }
}
else{
  helloworld=function(){ //赋值
    console.log("你好,世界");
  }
}
Copy after login

2. Recursive function

A recursive function is formed when a function calls itself by name (the same as C# and other languages, so the core idea of ​​the program is similar, except for some differences in syntax. Learn the basics of a language well and learn Others will be much easier). Take a classic recursion interview question. The rules for a column of numbers are as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34... To find the 30th digit, use recursion Algorithm implementation, the code is as follows:

   function foo(n) {
      if (n <= 0)
        return 0;
      else if (n > 0 && n <= 2)
        return 1;
      else
        return foo(n - 1) + foo(n - 2);
    }
Copy after login

Although this function seems to have no problem, the following code may cause it to go wrong:

   var foo1 = foo;
    foo = null;
    console.log(foo1(34));
Copy after login

The above code first saves the foo() function in the variable foo1, and then sets the foo variable to null. As a result, there is only one reference to the original function. But when foo1() is called next, since foo() must be executed and foo is already null, an error will occur; in this case, using arguments.callee can solve this problem. arguments.callee is a pointer to the function being executed, so you can use it to implement recursive calls to the function

 function foo(n) {
      if (n <= 0)
        return 0;
      else if (n > 0 && n <= 2)
        return 1;
      else
        return arguments.callee(n - 1) + arguments.callee(n - 2);
    }
Copy after login

You can also use named function expressions to achieve the same result. For example:

 var foo = (function f(n) {
      if (n <= 0)
        return 0;
      else if (n > 0 && n <= 2)
        return 1;
      else
        return f(n - 1) + f(n - 2);
    });
Copy after login

3. Closure

3.1 Closure means the right to access another function scope A common way to create a closure is to create a function inside a function. To understand closures, you must first understand the scope of JavaScript special variables. The scope of variables is nothing more than two types, global variables and local variables; Next, write a few demos to express it intuitively;

Read global variables directly inside the function:

 var n = 100; //定义一个全局变量
    function fn() {
      console.log(n); //函数内部直接读取全局变量
    }

    fn();
Copy after login

Local variables cannot be read directly outside the function:

    function fn() {
      var n = 100;
    }

    console.log(n); //n is not defined
Copy after login

There is something to note here, which is to declare it inside the function When using variables, be sure to use var. If it is not used, it will become a global variable:

 function fn() {
       n = 100;
    }
    fn();
    console.log(n); //100
Copy after login

Sometimes we need to get the variables declared inside the function, So you can use the common way of creating closures mentioned above to create another function inside the function:

   function fn() {
      n = 100;

      function fn1() {
        console.log(n);
      }

      fn1();
    }
    fn(); //100
Copy after login

In the above code, function fn1 is Included inside function fn, all local variables inside fm are visible to fn1. But the reverse doesn't work. The local variables inside fn1 are invisible to fn. This is the unique "chain scope" structure of the Javascript language. The child object will look up the variables of all parent objects level by level. Therefore, all variables of the parent object are visible to the child object, but not vice versa.

It turns out that fn1 can read the internal variables of fn, so as long as fn1 is used as the return value, we can read the variables of fn externally

function fn() {
      n = 100;

      function fn1() {
        console.log(n);
      }

      return fn1;
    }
    
    var result=fn();
    result(); //100
Copy after login

Here fn1 is a closure, and a closure is a function that can read the internal variables of other functions. Since in the Javascript language, only subfunctions within 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 the function with the outside of the function.

3.2 The purpose of closure

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 at all times. in memory. As shown in the following code:

function fn() {
      n = 100;

      nadd = function () {
        n += 1;
      }

      function fn1() {
        console.log(n);
      }

      return fn1;
    }

    var result = fn();
    result(); //100
    nadd();
    result(); //101
Copy after login

注意:由于闭包函数会携带包含它的函数的作用域,因此会比其他函数占用更多的内存,过度使用闭包可能会导致内存占用过多,所以在退出函数之前,将不使用的局部变量全部删除。

四、块级作用域

块级作用域(又称为私有作用域)的匿名函数的语法如下所示:

(function(){
   //块级作用域
})();
Copy after login

无论在什么地方,只要临时需要一些变量,就可以使用私有作用域,比如:

(function () {
      var now = new Date();
      if (now.getMonth() == 0 && now.getDate() == 1) {
        alert("新年快乐");
      }
    })();
Copy after login

把上面这段代码放到全局作用域中,如果到了1月1日就会弹出“新年快乐”的祝福;这种技术经常在全局作用域中被用在函数外部,从而限制向全局作用域中添加过多的变量和函数。一般来说,我们都应该尽量少向全局作用域中添加变量和函数。在一个由很多开发人员共同参与的大型应用程序中,过多的全局变量和函数很容易导致命名冲突。而通过创建私用作用域,每个开发人员既可以使用自己的变量,又不必担心搞乱全局作用域。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

关于如何优化你的JS代码(图文教程)

畅谈HTML+CSS+JS(详细讲解)

原生JS+AJAX做出三级联动效果(附代码)

The above is the detailed content of JavaScript function expressions (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles