Totally right about constructors and return type. Thanks for giving me the chance to talk about this a bit more.
Indeed, what I see as the very problem with new
and constructors, is the peculiar behavior of
- The this pointer
- The return type
for constructors.
You yourself, in the rush of the moment, are making a bit of confusion in your counter example:
function Person() {};
var p = new Person(); //assign a new Person object to p
has a totally different behavior from
function Person() { return this; }
var p = Person(); //assign the global object to p
Back to your example, for sake of completeness, say we use an explicit return statement (return this;
), what is going to be returned when we use var p = Person('foo')
(without new)?
Not a new Person
, of course, nor undefined
.
To let everybody else understand: since when we call a function as a function (i.e. not as a method, constructor or by using apply/call) this
is set to the global object, then window
(in browsers, ofc) is returned.
If we use strict mode
however, this
will be set to null instead, and an error will be thrown this.getName = ...
.
Now, on the other hand, by using that safe constructor pattern,
if (!(this instanceof Person)) {
return new Person(name);
}
a Person object will be returned both in strict mode
(ES5
and newer versions) and “legacy” mode, no matter if the caller uses new
or forgets about it.
That’s why this pattern is safe, and the other is error prone.
Now, JavaScript allows you to do the same thing in many different ways, and one is free to like enforcing the use of constructors and new.
Personally, I think this is trying to make it more similar to Java, and in fact it astray you from the prototypical pattern in favor to something similar to the class pattern.
You are also totally free not to care about lazy programmers, and just hope they never forget to prepend new
to your library’s constructors.
But I guess it is good to know you have an easy alternative to make your code more robust - personally I like that.
Again, you all don’t take have to take my word on that: Crockford himself advice against the use of constructors in his videos and his book (Javascript: the good parts - new
is actually included in the bad parts), and you can check another great book, Javascript Patterns by Stefanov for the safe constructor pattern.
About lazyness in coding, great video featuring Marc Stiegler https://www.youtube.com/watch?v=eL5o4PFuxTY
Bottom line (among others) let’s make it easy (and harmless) for programmers to be lazy
BTW, thanks for the advice, I will try to revise the examples and make them more focused and simpler.
Have a nice day!