Effect of assigning JavaScript function to variable
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
In JavaScript, I can define a function and assign it to a variable:
var myVar = function myFunc(){};
or define the function standalone:
function myFunc(){};
What are the use cases for the first approach?
functions declared to variables are not hoisted to the top of the scope
function run() {
fn1(); // logs "hi"
fn2(); // error
function fn1 () { console.log("hi"); }
var fn2 = function () { console.log("hi again"); };
}
See this previous related answer. Are named functions or anonymous functions preferred in JavaScript?
This will end up looking similar to this after the parse runs through it
function run() {
function fn1 () { console.log("hi"); }
var fn2;
fn1(); // logs "hi"
fn2(); // error
fn2 = function () { console.log("hi again"); };
}
链接地址: http://www.djcxy.com/p/96296.html
上一篇: var functionName = function(){} vs function functionName(){}