Skip to content

Comment on Stop Using Constructors in JS (2012)

Comments

The curse of Javascript:

1) Someone explains how using modern techniques can make for more maintainable code with less coupling and more reusability.

2) Someone pops in and notes that "Feature X/Y/Z is not available for browsers A, B, C"

In the end, people will keep on using the old constructors because they work all the time everywhere. And this is bad because this article does make a whole lot of sense.

I often have the very same problem when I look at https://developer.mozilla.org/en/docs/Web/JavaScript/Referen... or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... where lots of the most interesting functions of said prototypes are marked as "experimental" and most likely won't be universally available before 2016 or so.

The article describes a way to avoid the use of 'new' entirely, but you can just as easily get the advantages of factory encapsulation without the use of Object.create.

    var MyModule = (function() {

        function OneImplementation() {}
        function OtherImplementation() {}

        function factoryMethod() {
            if (foobar) {
                return new OneImplementation();
            }
            else {
                return new OtherImplementation();
            }
        }

        return {
            create: factoryMethod
        };
    })();
As long as the use of new doesn't leak out of the module you're getting all of the advantages. Upgrade to Object.create when you get the chance, but don't let that hold you back.

A number of these things are available in IE9 and older using https://github.com/es-shims/es5-shim (including Object.create that the article was talking about)

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.