匿名类实例----是一个坏主意吗? [英] Anonymous class instance ---- is it a bad idea?

查看:184
本文介绍了匿名类实例----是一个坏主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var entity = class {
}

但是我们也可以实例化:

 code> var entity = new class {
constructor(name){this.name = name; }
getName(){return this.name; }
}('Foo');
console.log(entity.getName()); // Foo

背后做了什么,它带来什么好处以及它还带来什么注意事项?

解决方案


匿名类实例 - 这是一个坏主意吗?


是的,一个非常糟糕的。只有新功能(){...} 一样糟糕的是在ES5



这种写作风格导致每次评估表达式时创建一个新的构造函数和原型对象。如果您使用此方法创建多个对象,那么它们将无法获得类/原型的优点。



如果您打算使用此模式创建单例对象,那么您将失败好。构造函数仍然创建,甚至可以访问 - 可以使用 new entity.constructor 轻松创建第二个实例,从而打破整个目的。



所以不要使用它。一个简单的对象字面容易写入,阅读和实例化:

  var entity = {
name:'Foo ',
getName(){return this.name; }
};
console.log(entity.name); // Foo

不要被其他语言所欺骗,其中新类模式是常见的,它与JavaScript中的工作方式非常不同。


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?

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.

这篇关于匿名类实例----是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆