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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3