gpt4 book ai didi

javascript - javascript构造函数的区别

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:57 26 4
gpt4 key购买 nike

除了解析构造函数之外,这两者之间有什么区别吗?

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;
};
};

两者都可以使用

var p = new Person("Yes",25,"Male");

第一个解析为 function(),后者解析为 person(),但我想知道使用其中一个是否有任何优势

最佳答案

就您所说的目的而言,它们是相同的。

唯一的区别是在第二个函数中,您可以从自身内部清楚地引用该函数。

正式

The language specification states :

FunctionExpression :

function Identifier(opt) ( FormalParameterListopt ) { FunctionBody }

函数表达式中的标识符(在本例中为 Person)是可选的

其原因稍后会在语言规范中解释:

NOTE The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

实践

您可以在两种情况下使用第二个选项:

当它使您的代码更易于理解时:

   (function removeBodyDivs(){
//does logic removing
//divs from the body
})();

可以比以下更容易理解:

   (function (){
//does logic removing
//divs from the body
})();

比如做递归的时候

  var f = function fib(n){
return n<2?2:(fib(n-1)+fib(n-2));
}

关于javascript - javascript构造函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com