Explicitly return value from constructor in javascript

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

In the above link, John Resig suggests calling and returning new foo in the constructor if the caller initially forgot.

which has some meaning for me, but then I get a severe error, because my constructor does not "always" return a value. Having got a little idea of ​​constructors in javascript, I stopped returning this because new automatically does this.

My question is should I ...

  • Do not use the described protective equipment?
  • return this to the end of my constructor?
  • A secret option that I don't know about?
+6
javascript constructor return-value
source share
1 answer

return this pointless because if the caller forgot to add new , then this will be a document, not an instance of foo . I usually run the constructor with if(! (this instanceof foo)) return new foo(); or something like that

Edit: after a more thorough reading, if you want to avoid severe errors, and you do it already, yes, return this at the end is usually a good idea

+4
source share

All Articles