除了解析构造函数之外,这两者之间有什么区别吗?
var Person = function(living, age, gender) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {
return this.gender;
};
};
var Person = function Person(living, age, gender) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {
return this.gender;
};
};
Run Code Online (Sandbox Code Playgroud)
两者都可以使用
var p = new Person("Yes",25,"Male");
Run Code Online (Sandbox Code Playgroud)
第一个解析为function(),后者解析为person(),但我想知道使用一个优于另一个是否有任何优势
它们与您所说的目的完全相同.
唯一的区别是,在第二个函数内部,您可以从内部对函数进行干净的引用.
FunctionExpression:
function Identifier(opt)(FormalParameterListopt){FunctionBody}
Person函数表达式中的标识符(在本例中)是可选的
稍后在语言规范中解释了其原因:
注意 FunctionExpression中的标识符可以从FunctionExpression的FunctionBody内部引用,以允许函数递归调用自身.但是,与FunctionDeclaration不同,FunctionExpression中的标识符不能被引用,也不会影响包含FunctionExpression的范围.
您可以在两种情况下使用第二个选项:
当它使您的代码更容易理解时:
(function removeBodyDivs(){
//does logic removing
//divs from the body
})();
Run Code Online (Sandbox Code Playgroud)
可以比以下更容易理解:
(function (){
//does logic removing
//divs from the body
})();
Run Code Online (Sandbox Code Playgroud)
例如,在进行递归时
var f = function fib(n){
return n<2?2:(fib(n-1)+fib(n-2));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |