我最近开始保持别人的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 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
希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。
区别在于,函数One 是一种函数表达式,因此只有在到达该行时才定义,而函数Two 是一种函数声明,并在其周围函数或脚本执行后才定义。
例如,函数表达式:
// TypeError: functionOne 不是函数函数One(); var 函数One = 函数() { console.log(“Hello!”); };
还有一个功能声明:
// 输出: “Hello!”函数Two();函数函数Two() { console.log(“Hello!”); }
“使用严格”; { // 注意此区块! 函数三() { console.log(“Hello!”); } } 函数三(); // 参考错误
当原始忍者物体被移除时,测试失败(第13页)
function assert(predicate, message) { if(!predicate) { throw new Error(message); } }
var ninja = {
yell: function(n){
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
}
};
assert( ninja.yell(4) == "hiyaaaa", "A single object isn't too bad, either." );
var samurai = { yell: ninja.yell };
var ninja = null;
try {
samurai.yell(4);
} catch(e){
assert( false, "Uh, this isn't good! Where'd ninja.yell go?" );
}
function assert(predicate, message) { if(!predicate) { throw new Error(message); } }
var ninja = {
yell: function yell(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}
};
assert( ninja.yell(4) == "hiyaaaa", "Works as we would expect it to!" );
var samurai = { yell: ninja.yell };
var ninja = {};
assert( samurai.yell(4) == "hiyaaaa", "The method correctly calls itself." );
console.log(samurai.yell(4));
第一個(函數 doSomething(x))應該是對象評分的一部分。
你可能想知道什么是函数声明和函数表达式。
function foo() {
return 3;
}
ECMA 5(13.0)定义合成为函数识别器(FormalParameterListopt ) { FunctionBody }
在上述情况下,函数名称在其范围内和其父母范围内可见(否则它将是不可访问的)。
在函数表达中
函数表达式定义函数作为一个更大的表达式合成的一部分(通常是一个变量任务)。函数表达式可以命名或匿名。
// Anonymous function expression
var a = function() {
return 3;
}
// Named function expression
var a = function foo() {
return 3;
}
// Self-invoking function expression
(function foo() {
alert("hello!");
})();
ECMA 5 (13.0) 定义合成为函数 Identifieropt ( FormalParameterListopt ) { FunctionBody }