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 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值