Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is returned from a constructor?

Tags:

javascript

If I return some value or object in constructor function, what will the var get?

function MyConstroctor() {     //what in case when return 5;     //what in case when return someObject; }  var n = new MyConstroctor(); 

what n will get in both cases?

Actually its a quiz question, what will be the answer?
What is returned from a custom object constructor?
a)The newly-instantiated object
b)undefined - constructors do not return values
c)Whatever is the return statement
d)Whatever is the return statement; the newly-instantiated object if no return statement

like image 891
coure2011 Avatar asked Jul 28 '10 05:07

coure2011


1 Answers

Short Answer

The constructor returns the this object.

function Car() {    this.num_wheels = 4; }  // car = { num_wheels:4 }; var car = new Car(); 

Long Answer

By the Javascript spec, when a function is invoked with new, Javascript creates a new object, then sets the "constructor" property of that object to the function invoked, and finally assigns that object to the name this. You then have access to the this object from the body of the function.

Once the function body is executed, Javascript will return:

ANY object if the type of the returned value is object:

function Car(){   this.num_wheels = 4;   return { num_wheels:37 }; }  var car = new Car(); alert(car.num_wheels); // 37 

The this object if the function has no return statement OR if the function returns a value of a type other than object:

function Car() {   this.num_wheels = 4;   return 'VROOM'; }  var car = new Car(); alert(car.num_wheels); // 4 alert(Car()); // No 'new', so the alert will show 'VROOM' 
like image 151
Kenan Banks Avatar answered Oct 14 '22 06:10

Kenan Banks