JavaScript Function Declarations vs. Function Expressions

原创转载请注明出处:http://agilestyle.iteye.com/blog/2341737

There are actually two literal forms of functions.

The first is a function declaration, which begins with the function keyword and includes the name of the function immediately following it. The contents of the function are enclosed in braces, as shown in this declaration:

function add(num1, num2) {
    return num1 + num2;
}

The second form is a function expression, which doesn't require a name after function. These functions are considered anonymous because the function object itself has no name. Instead, function expressions are typically referenced via a variable or property, as in this expression:

var add = function(num1, num2) {
    return num1 + num2;
};

Although these two forms are quite similar, they differ in a very important way. Function declarations are hoisted to the top of the context (either the function in which the declaration occurs or the global scope) when the code is executed. That means you can actually define a function after it is used in code without generating an error. For example:

var result = add(5, 5);

function add(num1, num2) {
    return num1 + num2;
}

console.log(result);    // 10

This code might look like it will cause an error, but it works just fine. That's because the JavaScript engine hoists the function declaration to the top and actually executes the code as if it were written like this:

function add(num1, num2) {
    return num1 + num2;
}

var result = add(5, 5);

console.log(result);    // 10

Function hoisting happens only for function declarations because the function name is known ahead of time. Function expressions, on the other hand, cannot be hoisted because the functions can be referenced only through a variable. So this code causes an error:

// error!
var result = add(5, 5);
var add = function (num1, num2) {
    return num1 + num2;
};

Reference

Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014 

猜你喜欢

转载自agilestyle.iteye.com/blog/2341737