1

I'm used to a javascript object constructors looking like this

function person(first, last) {
   this.firstName = first;
   this.lastName = last;
}

var dude = new person("the", "dude");

But sometimes I see the constructor return "this", like so

function person(first, last) {
   this.firstName = first;
   this.lastName = last;
   return this;
}

What's up with returning this at the end?

j08691
  • 204,283
  • 31
  • 260
  • 272
User314159
  • 7,733
  • 9
  • 39
  • 63

3 Answers3

3

There's no point in returning this from a constructor, but you are allowed to return any object you'd like. If no object is explicitly returned, this is implicitly returned.

A possible use case is:

function person(first, last) {
  if(!(this instanceof person)) {
    return new person(first, last);
  }
  this.first = first;
  this.last = last;
}

var person1 = new person('first', 'person');
var person2 = person('second', 'person'); // <- without "new"

console.log(person1, person2);
Amit
  • 45,440
  • 9
  • 78
  • 110
  • Good example, I would still stay away from it :); I posted about the ["forgetting to call `new`" problem](http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html) for anyone that wants further explanation as to what's going on with this question. – Ruan Mendes Dec 09 '15 at 22:10
0

The only case that I know it could mean something is if you instantiate your objects in the following manner;

person.call(Object.create(person.prototype), 'Jack', 'Brown');

The above example requires that you return this;

What can be done, but should be avoided, is to return a different object than this

function person(first, last) {
    return {first: first, last: last};
}
(new Person() ) instanceof Person // false
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

this is returned so the caller can chain calls together.

console.log(new person('First', 'Last').firstName);

DaveB
  • 9,470
  • 4
  • 39
  • 66