Reputation: 3070
I have a function for creating objects as follows:
function person() {
this.name = "test person";
}
var me = new person();
Now I'm planning to wrap this function into another one like this for assertion purposes.
function reliable_person() {
/* do check on params if any*/
return new person();
}
var me = new reliable_person();
Is this a possible approach? I know there are better ways for such checks within the constructor itself, but is this a reliable solution?
Upvotes: 1
Views: 311
Reputation: 522005
Invoking a function with new
constructs a new object and uses the given function to initialise the object. Something that's a bit special about this is that if you return
a non-primitive value, like an object, from that function, that value will be used as the new object instead. Sounds complicated, but what it boils down to is that reliable_person()
and new reliable_person()
result in the exact same thing, because you're returning an object from it. So using new
with that function is pointless.
Removing the superfluous new
from it, all that's left is a normal function which returns an object (a "factory function"). Yes, that works and is "reliable".
Upvotes: 2