匿名类实例 ---- 这是一个坏主意吗? [英] Anonymous class instance ---- is it a bad idea?
问题描述
在 ES6 中我们可以做匿名类:
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?
推荐答案
匿名类实例——这是个坏主意吗?
Anonymous class instance — is it a bad idea?
是的,非常糟糕.就像 new function() { ... }
在 ES5 中一样糟糕.
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.
如果你打算用这个模式创建一个单例对象,你也失败了.构造函数仍然被创建,它甚至可以访问 - 可以使用 new entity.constructor
轻松创建第二个实例,从而破坏了整个目的.
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
不要被new class
模式很常见的其他语言所迷惑,它在那里的工作方式与在 JavaScript 中非常不同.
Don't be fooled by other languages where the new class
pattern is common, it works very different there than in JavaScript.
这篇关于匿名类实例 ---- 这是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!