search
HomeWeb Front-endJS TutorialJavaScript function expressions (graphic tutorial)

JavaScript function expressions (graphic tutorial)

May 19, 2018 am 10:52 AM
javascriptjsexpression

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){
   //函数体
}

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");
}

1.2 Function expression

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

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");
}

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("你好,世界");
  }
}

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);
    }

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));

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);
    }

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);
    });

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();

Local variables cannot be read directly outside the function:

    function fn() {
      var n = 100;
    }

    console.log(n); //n is not defined

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

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

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

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

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

 四、块级作用域

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

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

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

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

把上面这段代码放到全局作用域中,如果到了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
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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor