我最近开始保持别人的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
希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。
a = 10
output : 10
(1 + 3)
output = 4
声明/声明:不返回值的东西 示例:
if (1 > 2) {
// do something.
}
此分類上一篇
同样,我们有函数声明/声明 vs 函数表达 请举一个例子:
// test.js
var a = 10;
// function expression
var fun_expression = function() {
console.log("Running function Expression");
}
// funciton expression
function fun_declaration() {
console.log("Running function Statement");
}
重要:在JavaScript引擎运行上面的JS文件时会发生什么。
现在,假设我们更新JS到。
// test.js
console.log(a) //output: udefined (No error)
console.log(fun_expression) // output: undefined (No error)
console.log(fun_expression()) // output: Error. As we trying to invoke undefined.
console.log(fun_declaration()) // output: running function statement (As fun_declaration is already hoisted in the memory).
var a = 10;
// function expression
var fun_expression = function() {
console.log('Running function expression')
}
// function declaration
function fun_declaration() {
console.log('running function declaration')
}
console.log(a) // output: 10
console.log(fun_expression()) //output: Running function expression
console.log(fun_declaration()) //output: running function declaration
在评论中提到的结果,应该有助于理解函数表达与函数声明/声明之间的区别。
一个描述什么时候优先于第一种方法,而不是第二种方法,是当你需要避免超越一个函数的以前定义时。
与
if (condition){
function myfunction(){
// Some code
}
}
,这个定义的微功能将超越任何以前的定义,因为它将在时间段进行。
虽然
if (condition){
var myfunction = function (){
// Some code
}
}
正确的定义功能工作只有在条件满足时。