Difference in javascript constructors

Is there a difference between these 2 separately from the resolving constructor?

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

Both can be called using

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

The former allows functions (), where the latter permits person (), but I would like to know if there is any advantage to using one over the other

+4
source share
1 answer

They are identical for the goals you are talking about.

The only difference is that inside the second function you have a clean reference to the function from the inside.

Formally

The language specification states:

Function expression:

Function Identifier (opt) (FormalParameterListopt) {FunctionBody}

The identifier (in this case, Person ) in the function expression is optional

The rationale for this is explained a bit later in the language specification:

NOTE An identifier in a Function expression can be referenced from within a FunctionExpression FunctionBody function to call a function recursively. However, unlike FunctionDeclaration, the Identifier in the Function expression cannot reference and does not affect the scope of Expression.

On practice

You can use the second option in two situations:

When this makes your code clearer:

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

It may be clearer than:

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

When doing recursion, for example

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

Source: https://habr.com/ru/post/1482054/


All Articles