-2
function Person (name, eyeColor, age) {

this.name = name;
this.eyeColor = eyeColor;
this.age = age;
this.updateAge = function ()  {

return ++this.age;


};

}  


let person1 = new Person("kevin", "blue", 34); // normalli would have to return something but as im 
creating a new object 
let person2 = new Person("tom", "brown", 64);


console.log(person1);

Normally if i wanted let person1 to equal something from inside the function i would have to return something to it. Why do i not have to do that when creating a new object constructor. if i console.log person 1, it returns person 1 to me. Whereas if i were normally calling a function i would need it have to return something to me for that to be the assignment value of the variable. Also why are we returning from the method? But we dont return from inside the constructor function

thanks all

  • In general a constructor serves to populate your class fields so that those can be used in methods of that same class, if you wanted to return a person you should have a createPerson function which would build the person object., that said the constructor is the begining phase of class instantiation which automaticaly implies that you should not return in it – EugenSunic Aug 07 '20 at 08:32
  • Hey, you are talking with real people here! Please honor them by correctly used capital letters and markups. – peterh Aug 07 '20 at 22:48

1 Answers1

0

Please refer below document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

The new keyword does the following things:

  • Creates a blank, plain JavaScript object;
  • Links (sets the constructor of) this object to another object;
  • Passes the newly created object from Step 1 as the this context;
  • Returns this if the function doesn't return an object.
Rahul Cv
  • 725
  • 5
  • 12