我最近开始保持别人的JavaScript代码,我正在修复错误,添加功能,也试图更新代码并使其更加一致。
以前的开发人员使用了两种方式来宣布功能,我无法解决是否有原因。
兩種方式是:
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
使用这两种不同的方法的原因是什么?每个方法的优点和缺点是什么?可以用一种方法做些什么,不能用另一种方法做些什么?
当原始忍者物体被移除时,测试失败(第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));
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 函数 与函数添加()
一个描述什么时候优先于第一种方法,而不是第二种方法,是当你需要避免超越一个函数的以前定义时。
与
if (condition){
function myfunction(){
// Some code
}
}
,这个定义的微功能将超越任何以前的定义,因为它将在时间段进行。
虽然
if (condition){
var myfunction = function (){
// Some code
}
}
正确的定义功能工作只有在条件满足时。
你在那里发布的两个代码剪辑,几乎所有目的都会以相同的方式行事。
然而,行为的差异是,在第一个变量(有函数One = 函数() {}),该函数只能在代码中的那个点之后被称为。
第二个选项(函数Two()),函数可用于代码,运行在函数被宣布的地方。
这是因为第一种变量,函数在运行时分配给变量foo;第二种函数在运行时分配给这个识别器,foo。
更多技术信息
JavaScript 有三种方式来定义功能。
你的第一个剪辑显示一个函数表达式. 这意味着使用“函数”操作员创建一个函数 - 该操作员的结果可以存储在任何变量或对象属性. 函数表达式是强大的这种方式. 函数表达式经常被称为“匿名函数”,因为它不需要一个名字, 你的第二个例子是一个函数声明。
这就是所谓的函数表达:
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
希望这有助于解释函数表达和函数声明之间的区别,以及如何使用它们。