Home > Web Front-end > JS Tutorial > JavaScript advanced series - function declarations and expressions

JavaScript advanced series - function declarations and expressions

黄舟
Release: 2017-02-08 10:00:36
Original
1195 people have browsed it
  • Function declaration

  • Function assignment expression

  • Assignment expression for named function


# Functions are first-class objects in JavaScript, which means they can be passed around like any other value. A common usage is to pass an anonymous function as a callback function into an asynchronous function.

Function declaration

function foo() {}
Copy after login

The above method will be parsed (hoisted) before execution, so it exists anywhere in the current context, even if it is called above the function definition body, it is correct of.

foo(); // 正常运行,因为foo在代码运行前已经被创建
function foo() {
Copy after login

Function assignment expression

var foo = function() {};
Copy after login

This example assigns an anonymous function to variable foo.

foo; // 'undefined'
foo(); // 出错:TypeError
var foo = function() {};
Copy after login

Since var defines a declaration statement, the variable foo is parsed before the code is run, so the foo variable has already been defined when the code is running.

But since the assignment statement is only executed at runtime, the value of foo defaults to undefined before the corresponding code is executed.

Assignment expression of named function

Another special case is to assign the named function to a variable.

var foo = function bar() {
    bar(); // 正常运行
}
bar(); // 出错:ReferenceError
Copy after login

bar The function declaration is invisible outside, because we have assigned the function to foo; however, it is still visible inside bar. This is due to JavaScript's naming processing. Function names are always visible within functions.

Note: In browsers IE8 and below, bar is also visible externally because the browser incorrectly parses the named function assignment expression and parses it into two functions foo and bar


The above is the content of the JavaScript advanced series - function declarations and expressions. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template