griotspeak
griotspeak

Reputation: 13247

Explicitly Returning a value from a constructor in javascript

http://ejohn.org/blog/building-a-javascript-library/

In the above link John Resig Suggests calling and returning new foo in a constructor if the caller originally forgot to.

that makes some sense to me, but then I get a strict error because my constructor does not 'always' return a value. Upon gaining a little understanding of constructors in javascript, i stopped returning this because new automatically does that.

My question is, should I ...

  1. Not use the defensive technique described?
  2. return this at the end of my constructor?
  3. Mystery option that I am ignorant of?

Upvotes: 6

Views: 753

Answers (1)

tobyodavies
tobyodavies

Reputation: 28099

returning this is pointless because if the caller forgot to add new then this will be the document, not an instance of foo. What i usually do is start a constructor with if(! (this instanceof foo)) return new foo(); or something to that effect

Edit: after a more careful read, if you want to avoid strict errors and you are doing this already, yes, return this at the end is usually a good idea

Upvotes: 4

Related Questions