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?

2
  • 1
    It's not necessary, the programmer didn't understand this. Commented Dec 9, 2015 at 22:02
  • Please go to the link: stackoverflow.com/questions/8300844/… Commented Dec 9, 2015 at 22:17

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Good example, I would still stay away from it :); I posted about the "forgetting to call new" problem for anyone that wants further explanation as to what's going on with this question.
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

Comments

0

this is returned so the caller can chain calls together.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.