Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Steve Fan Avatar asked Aug 03 '16 09:08

Steve Fan


People also ask

Are anonymous classes bad practice?

Here, the anonymous ChangeLstener is passed to the register method of a ChangeManager. Doing so will automatically publish the enclosing class as well. This is definitely a bad practice.

Why would you use an anonymous class rather than an inner class?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

In what cases will Anonymous classes be useful?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.

Can we create instance of anonymous class?

Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. We may either extend an existing class or implement an interface.


1 Answers

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.

like image 153
Bergi Avatar answered Oct 23 '22 16:10

Bergi