我最近开始保持别人的JavaScript代码,我正在修复错误,添加功能,也试图更新代码并使其更加一致。
以前的开发人员使用了两种方式来宣布功能,我无法解决是否有原因。
兩種方式是:
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
使用这两种不同的方法的原因是什么?每个方法的优点和缺点是什么?可以用一种方法做些什么,不能用另一种方法做些什么?
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
希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。