Javascript; functions created by assigning to a variable?
This question already has an answer here:
This is called a function expression:
var foo = function() {}
and this is a function declaration:
function foo() {}
A major difference is that function declarations are "hoisted". Behind the scenes, a function declaration is "hoisted" to the top of its scope and assigned to a variable name - effectively the same as a function expression.
Consider this:
foo(); //logs 'abc'
function() {
console.log('abc');
}
That works fine because foo
will be hoisted. With a function expression, this will fail:
foo(); //foo is not defined!
var foo = function() {
console.log('abc');
}
One thing that's awesome about function expressions is that you can assign their value with an IIFE (Immediately Invoked Function Expression) and have private values and functions like this:
var myFunc = (function() {
function thisWillBeMyFunc() {
doOne();
doTwo();
doThree();
}
function doOne() {
console.log('Action 1!');
}
function doTwo() {
console.log('Action 2!');
}
function doThree() {
console.log('Action 3!');
}
return thisWillBeMyFunc;
}());
myFunc(); //logs the actions
doOne(); //error - not defined!
Live demo (click).
Oh, the wonderful power and flexibility of JavaScript!
There is another difference. The first creates a named function, the second option will create an anonymous function.
When you are viewing the stack trace the second option will appear as an anonymous function the first will appear named. You can see how the first approach would give you some insight when debugging.
Some further references here and here.
链接地址: http://www.djcxy.com/p/96294.html