Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

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

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...