Anonymous class instance ---- is it a bad idea?

25,511

Solution 1

Anonymous class instance — is it a bad idea?

Yes, a very bad one. Just as bad as new function() { … } was in ES5.

This writing style leads to the creation of a new constructor function and prototype object every time the expression is evaluated. If you create multiple objects with this approach, they will get none of the benefits of classes/prototypes.

If you intended this pattern to create a singleton object, you failed as well. The constructor is still created, and it is even accessible - a second instance can be easily created using new entity.constructor, defeating the whole purpose.

So don't use it ever. A simple object literal is much easier to write, read and instantiate:

var entity = {
    name: 'Foo',
    getName() { return this.name; }
};
console.log(entity.name); // Foo

Don't be fooled by other languages where the new class pattern is common, it works very different there than in JavaScript.

Solution 2

You might want anonymous classes if you know exactly what you're doing, you're creating a hierarchy of classes (i.e. things you want copies of) in a well-thought-out metaprogramming system, and there's no other elegant solution to extension, e.g.

{
    myImplementation: class extends MyBaseClass {
        someMethod(x) {
            super().someMethod(x);
            insert extended behavior
        }
    }
}

Of course you could implement the above with some abusive magic functions which use Object.assign:

{
    myImplementation: extendMagic(mySuper => ({
        someMethod(x) {
            mySuper.someMethod(x);
            insert extended behavior
        }
    }))
}

or find some better way to do what you're doing. But contrived use-cases will occasionally (though rarely) exist.

The use-cases are never great, but are most compelling when you need Class features which are harder to write with prototypical inheritance (and of course since Classes are sort of wrappers around prototypical inheritance, your use case boils down to wanting the syntactic sugar plus es6+ class features... do you want constructors and super and extends and staticmethod etc.... or not? Are you stuck working with classes which already exist, or can you write everything using Objects and asserts? And does it really need to be anonymous? These questions may help you decide.).

Share:
25,511
Steve Fan
Author by

Steve Fan

nope.avi

Updated on July 09, 2022

Comments

  • Steve Fan
    Steve Fan almost 2 years

    In ES6 we can do anonymous class:

    var entity = class {
    }
    

    But we can also instantiate it:

    var entity = new class {
        constructor(name) { this.name = name; }
        getName() { return this.name; }
    }('Foo');
    console.log(entity.getName()); // Foo
    

    What is done behind it, what advantage will it bring and what caveats will it also bring?