Sometimes I am supposed to call new Foo() to create a new foo object, but sometimes I can just call Foo() to create it.
In general, for a given function, how do I know which to use?
new keyword do?See this question.
new keyword?If the target function has a .prototype. and it doesn't return anything (or it returns this), then you should use new to get an object with that proto.  (Although some people recommend using Object.create(...) as a clearer alternative.)
or, if the target function assigns things to this.foo, and you don't think it is trying to set things on the global object, then you should call it with new.
new keyword?If you are calling a factory function to create a new object, then you do not need to use the new keyword.
A factory function will usually create the new object itself, and then return it.  It will create the object using { ... } or Object.create(...) or by calling another function, or even by using new itself.
new keyword?If you just call Foo() then the body of the Foo function will run with this pointing to the global object (or in strict mode, with this === undefined).  If the function assigns this.foo then these will end up modifying the global.  Is that what you wanted?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With