In ES6, the ability to define anonymous classes provides syntactic sugar for class declarations. While convenient, the immediate instantiation of such classes can lead to a plethora of issues.
When an anonymous class is instantiated immediately, JavaScript creates a new constructor function and prototype object dynamically. Each evaluation of the expression results in a distinct constructor function and prototype.
This practice has several significant drawbacks:
Lack of Reusability:
Unlike named classes, immediately instantiated anonymous classes create a new constructor and prototype each time. This means that multiple instances will not share the same prototype, losing the benefits of class inheritance and prototype sharing.
Singleton Fallacy:
If the intention behind using this pattern is to create a singleton object, it fails. The constructor function remains accessible, allowing for the creation of multiple instances using new entity.constructor.
The consensus is clear: immediately instantiated anonymous classes should be avoided. A simple object literal provides a more efficient and straightforward alternative:
var entity = { name: 'Foo', getName: function() { return this.name; } };
While the new class pattern is acceptable in some other languages, it behaves differently in JavaScript. The dynamic nature of JavaScript's class creation precludes the advantages these languages enjoy.
The above is the detailed content of Are Immediately Instantiated Anonymous Classes in ES6 a Bad Idea?. For more information, please follow other related articles on the PHP Chinese website!