Can someone clarify the difference between a constructor function and a factory function in Javascript.
When to use one instead of the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The basic difference is that a constructor function is used with the
newkeyword (which causes JavaScript to automatically create a new object, setthiswithin the function to that object, and return the object):A factory function is called like a “regular” function:
But for it to be considered a “factory” it would need to return a new instance of some object: you wouldn’t call it a “factory” function if it just returned a boolean or something. This does not happen automatically like with
new, but it does allow more flexibility for some cases.In a really simple example the functions referenced above might look something like this:
Of course you can make factory functions much more complicated than that simple example.
One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.