Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 419
griotspeak Avatar asked Jan 27 '11 02:01

griotspeak


1 Answers

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

like image 81
tobyodavies Avatar answered Oct 06 '22 00:10

tobyodavies