我最近开始保持别人的JavaScript代码,我正在修复错误,添加功能,也试图更新代码并使其更加一致。
以前的开发人员使用了两种方式来宣布功能,我无法解决是否有原因。
兩種方式是:
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
使用这两种不同的方法的原因是什么?每个方法的优点和缺点是什么?可以用一种方法做些什么,不能用另一种方法做些什么?
谈到全球背景,这两种说法和函数声明最终将为全球对象创造一个不可分割的财产,但两者的价值可以被夸张。
两种方式之间的微妙区别在于,当变量定位过程运行(在实际代码执行之前)时,与 var 所宣布的所有标识符将以未定义的标识符开始,并且由 FunctionDeclaration 所使用的标识符将从那时起可用,例如:
alert(typeof foo); // 'function', it's already available
alert(typeof bar); // 'undefined'
function foo () {}
var bar = function () {};
alert(typeof bar); // 'function'
function test () {}
test = null;
你的两个例子之间的另一个显而易见的区别是,第一个函数没有名字,而第二个函数有它,这在解体时可能非常有用(即检查一个呼叫板)。
此外,未透露的任务在严格模式下在 ECMAScript 5 上投下参考错误。
必须读一读:
名称 函数表达 解密
var add = undefined; try { console.log(“成功:”,添加(1, 1)); } catch(e) { console.log(“错误:” + e); } add = function(a, b){ return a + b; }
尝试 { console.log(“成功:”,添加(1, 1)); } catch(e) { console.log(“错误:” + e); } var add=function add(a, b){ return a + b; }
名称(名称)
函数函数的名称 thefuncname(){} 是函数名称,当它以这种方式宣布时。
var a = 函数 foobar(){}; console.log(a.name);
变量可变性
什么是“最接近的区块”
正常是 add=function(){}
正常功能添加({})
功能
Arrow 函数与 var add=函数()
Arrow 函数 与函数添加()
这就是所谓的函数表达:
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
希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。