Anonymous class instance -— is it a bad idea?

泄露秘密 提交于 2019-11-26 02:58:02

问题


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?


回答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.




回答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.).



来源:https://stackoverflow.com/questions/38739499/anonymous-class-instance-is-it-a-bad-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!