Here is a regular constructor function:
var Hello = function (name) {
this.name = name;
};
When used with new, you get what you would expect:
new Hello('Mark'); // { name: Mark } and hello.constructor is [Function Hello] etc.
Let's modify the constructor to be a bit more explict. If no return is given in a JS function, undefined
is implied.
Hello = function (name) {
this.name = name;
return undefined;
};
new Hello('Mark'); // Exactly the same as before.
That's a little weird when you think about it. We're telling it to return undefined
but we get an object instead. It's
tempting to think at this point that the return simply gets ignored when using new, but that's not entirely true. In fact, this
only applies to primitive types (null
, undefined
, numbers, string and booleans). When you return a reference type
(functions, objects, arrays etc.) the return is not ignored!
Hello = function (name) {
this.name = name;
return [0, 1, 2, 3, 4, this.name];
}
new Hello('Mark'); // [0, 1, 2, 3, 4, 'Mark']
It's very hard to see a case for which returning like this is actually useful. Some arcane applications may exist though. If you can think of something, please leave a comment.