5

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user5283721
  • 607
  • 6
  • 16
  • For first question, yes you can return something/anything from a constructor function as you do with any other function declaration. Constructor functions are at the end of the day, function declarations.. – Sudhansu Choudhary Feb 10 '16 at 09:31
  • function MyClass(){ this.a = 10; return 20; // Interesting part } var obj1 = new MyClass(); console.log(obj1.a); // 10 works as expected. console.log(obj1.constructor()); // 20 – Rahul Sharma Feb 20 '18 at 12:31

2 Answers2

4

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

When the code new Foo(...) is executed, the following things happen:

1- A new object is created, inheriting from Foo.prototype.

2- The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.

3- The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

function Car() {}
car1 = new Car();

console.log(car1.color);    // undefined

Car.prototype.color = null;
console.log(car1.color);    // null

car1.color = "black";
console.log(car1.color);   // black

You can find a complete description Here

Alireza
  • 126
  • 1
  • 14