我最近开始保持别人的JavaScript代码,我正在修复错误,添加功能,也试图更新代码并使其更加一致。

以前的开发人员使用了两种方式来宣布功能,我无法解决是否有原因。

兩種方式是:

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

使用这两种不同的方法的原因是什么?每个方法的优点和缺点是什么?可以用一种方法做些什么,不能用另一种方法做些什么?


当前回答

這只是兩種可能的方式來宣告功能,第二種方式,你可以在宣告之前使用功能。

其他回答

这就是所谓的函数表达:

var getRectArea = function(width, height) {
    return width * height;
};

console.log("Area of Rectangle: " + getRectArea(3,4));
// This should return the following result in the console: 
// Area of Rectangle: 12

这就是所谓的功能声明:

var w = 5;
var h = 6;

function RectArea(width, height) {  //declaring the function
  return area = width * height;
}                                   //note you do not need ; after }

RectArea(w,h);                      //calling or executing the function
console.log("Area of Rectangle: " + area);
// This should return the following result in the console: 
// Area of Rectangle: 30

希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。

格雷格的答案足够好,但我仍然想添加一些我刚才学会了观看杜格拉斯·克罗克福德的视频。

功能表达:

var foo = function foo() {};

功能声明:

function foo() {};

函数声明仅仅是函数值的每个声明的短片。

因此

function foo() {};

扩展到

var foo = function foo() {};

它进一步扩展到:

var foo = undefined;
foo = function foo() {};

两者都被推到代码的顶部。

此分類上一篇

新函数()可以用来将函数的身体转移到一条线上,因此可以用来创建动态函数,也可以通过脚本而不执行脚本。

var func = new Function("x", "y", "return x*y;");
function secondFunction(){
   var result;
   result = func(10,20);
   console.log ( result );
}

secondFunction()

我正在添加自己的答案只是因为其他每个人都彻底覆盖了包装部分。

我想知道哪种方式是更好的很长一段时间,现在,感谢 http://jsperf.com 现在我知道:)

此分類上一篇

功能声明更快,而这在Web Dev中真的很重要吗? ;)

這只是兩種可能的方式來宣告功能,第二種方式,你可以在宣告之前使用功能。