Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript constructor return values [duplicate]

Consider the following code:

function Foo() {
  return "something";
}

var foo = new Foo(); 

According to the experts in JavaScript, they say that return "nothing" or just "this" from a constructor. Whats the reason for this?

I am aware that when used "new", the "this" would be set to the prototype object of the constructor but not able to understand this point alone.

like image 699
user5283721 Avatar asked Feb 10 '16 09:02

user5283721


1 Answers

That particular code will throw a ReferenceError because something is not declared.

You should either return this or have no return statement at all in a constructor function because otherwise you will have constructed a new instance of the class (the value of this, and the default return value) and then thrown it away.

I am aware that when used "new", the "this" would be set to the prototype object of the constructor

Incorrect. It will be set to an instance of the constructor.

like image 81
Quentin Avatar answered Sep 20 '22 00:09

Quentin