通过将函数放入变量中来获得JavaScript优势?

问题描述:

我已经看到最近的代码示例将函数放入变量中,然后像正常一样调用函数。通过将函数放入变量中来获得JavaScript优势?

如:

var myFunctionName = function() { 
    Code Here... 
} 

myFunctionName(); 

我敢肯定有很多更高级的方案的优势,但我只是好奇。

+2

阅读从第一个答案的文章 - http://stackoverflow.com/questions/1013385/what-is-the-difference-between- a-function-expression-vs-declaration-in-javascript 直接链接到文章 - http://kangax.github.com/nfe/ – leebriggs 2011-02-16 23:16:14

没有优势,你没有放置一个函数里面一个变量,你只是简单地命名的功能不同。

function foo() { /* ... */ } 
var foo = function() { /* ... */ } 

除了一件事情之外,它们完全一样。

这工作:

foo("Hello!"); 
/* Later on... */ 
function foo() { /* ... */ } 

这不起作用:

foo("Hello!"); 
/* Later on... */ 
var foo = function() { /* ... */ } 

的JavaScript解释器将运行前预处理所有function foo的和他们推到程序,使它们的顶部可用但不会这样做var foo = function的。

+1

对于一点思考练习,var foo = function bar();酒吧=== foo? – leebriggs 2011-02-16 23:36:01

+0

@leeeb:不,“foo!== bar”。 – 2011-02-17 01:03:29

+0

感谢您的帮助! – Qcom 2011-02-17 01:57:20

有些事情你可以用一个函数表达式来做,你不能用声明。

  • 它可以被立即调用,并存储在变量

  • 如果您在全局命名空间是没有返回值,你可以排除var关键字来创建一个全球性的


编辑:

以下是立即调用的示例。它向myFunctionName变量返回一个函数,该变量可以访问立即调用的函数中的变量和参数范围。

var myFunctionName = function(v) { 
     // do something with "v" and some scoped variables 
     // return a function that has access to the scoped variables 

    return function() { 
     // this function does something with the scoped variables 
    }; 
}('someVal'); 

    // now this function is the only one that has access 
    // to the variables that were scoped in the outer expression. 
myFunctionName(); 

这里就是一个函数保持一个数值的例子。您可以重复调用该函数,并为其添加一个数字以添加到计数中。它将始终引用当前值,因此每个呼叫都是累积的。

实施例:http://jsfiddle.net/5uuLa/1/

var counter = function(value) { 

    return function(addValue) { 
     value += ~~addValue; 
     return value; 
    }; 
}(10); // initialize with a value 

    // each call builds on the result of the previous  
console.log(counter(2)); // 12 
console.log(counter(5)); // 17 
console.log(counter(3)); // 20 
console.log(counter(7)); // 27 
console.log(counter(1)); // 28 

这就是所谓的函数表达式,它具有比函数声明略微不同的行为。除此之外,当涉及到它时,它的行为会有所不同。举例来说,如果你这样做:

var myFunctionName = function() { 
    Code Here... 
} 

不能调用或引用函数,直到你已经被分配之后,而

function myFunctionName() { 
    Code Here... 
} 

可以在同一范围内被称为任何地方,它甚至前声明。这是因为JavaScript中的一个叫做“提升”的特性,所有函数声明都移到了代码块的后面。

另请参见:

What is the difference between a function expression vs declaration in JavaScript?

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting