6

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?

1 Answer 1

4

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

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

2 Comments

right, that is the suggestion that led me to the question. If I explicitly return during an error, I get a strict warning because i implicitly return when all goes well
yep, so returning this if all goes well is probably a good idea

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.