简体   繁体   English

如何在 JavaScript 中动态创建 class 实例?

[英]How do I dynamically create class instances in JavaScript?

Let's say I have an array of defined classes假设我有一组已定义的类

class Dick { };
class Duck { };
class Dear { };

const arr = [Dick, Duck, Dear];

And I also have an object我还有一个 object

const obj = {};

And I wanted to define a function that would take that object and that array and apply some magic then return a new object like this.我想定义一个 function ,它将采用 object 和该数组并应用一些魔法,然后像这样返回一个新的 object。 In this example, this new created object has properties like the class names above (and the first letter of each became lowercase) and every single property have a value of the instance of that class.在此示例中,这个新创建的 object 具有类似于上述 class 名称的属性(并且每个属性的第一个字母变为小写),并且每个属性都具有该 class 实例的值。 Is it possible to do in JavaScript?可以在 JavaScript 中做吗?

obj = magicFunction(obj, arr);


console.log(obj)
/*
{
 dick: <instance of the class Dick>,
 duck: <instance of the class Duck>,
 dear: <instance of the class Dear>
 ...
}
*/

NOTE:笔记:

<instance of the class... > is NOT a string , it's a real instance. <instance of the class... > is NOT a string ,它是一个真实的实例。

Perhaps this is what you are looking for?也许这就是你要找的?

class Dick { };
class Duck { };
class Dear { };

const dict = { Dick, Duck, Dear };
function magicFunction(obj={}, classes) {
  let results = {};
  for (let key in classes) {
    results[key.toLowerCase()] = new classes[key](obj)
  }
  return results;
}

let obj = {};
obj = magicFunction(obj, dict);
console.log(obj);

Changed the arr to a dictionary using destructuring to preserve the class names.使用解构将 arr 更改为字典以保留 class 名称。

The original obj is passed in to each class's constructor;原始的obj被传入每个类的构造函数; allowing you to initialize all of them with the same values, all at once!允许您一次用相同的值初始化它们!

You can get class name by using instance.constructor.name and combine that with reduce method to return the desired result.您可以使用instance.constructor.name获取 class 名称并将其与reduce方法结合以返回所需的结果。

 class Dick {}; class Duck {}; class Dear {}; const arr = [Dick, Duck, Dear]; const obj = arr.reduce((r, Cls) => { const inst = new Cls(); const key = inst.constructor.name.toLowerCase() r[key] = inst; return r; }, {}) console.log(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM