javascript - 使用参数字典调用类的构造函数

标签 javascript ecmascript-6

我有一个类,它有一个需要三个参数的构造函数。我的代码中的一个函数有一个字典,键是参数的确切名称,值是它们的值。有没有办法使用这个字典调用构造函数,以便键自动匹配?还是手动将每个值放入构造函数参数中的唯一解决方案?

class ItemDrop {
   constructor(id,x,y){
        this.id = id;
        this.x = x;
        this.y = y;
   }
}

在另一个文件中

var params = {
    "id" : "2837",
    "x" : 50,
    "y" : 100
}  
var itemdrop = new ItemDrop(params) // how would i do this?

澄清一下,我不想跑

var itemdrop = new ItemDrop(params['id'],params['x'],params['y'])

除非没有更清洁的选项,因为我将对许多不同的类多次执行类似的操作。

最佳答案

如果保证调用的构造函数只带有所需的属性,那么您可以使用Object.assign 将参数中的所有属性分配给实例(this ):

class ItemDrop {
  constructor(params) {
    Object.assign(this, params);
  }
}

const params = {
  "id": "2837",
  "x": 50,
  "y": 100
}

const instance = new ItemDrop(params);
console.log(instance);

为了将三个参数保留在构造函数中,没有办法将每个属性名称重复两次,并且必须对 params 中的属性进行排序,以便将它们正确地分布到构造函数中:

class ItemDrop {
  constructor(id, x, y) {
    Object.assign(this, { id, x, y });
  }
}

const params = {
  "id": "2837",
  "x": 50,
  "y": 100
}

const instance = new ItemDrop(...Object.values(params));
console.log(instance);

关于javascript - 使用参数字典调用类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927490/

相关文章:

javascript - 如何检索旧文本并从总数中减去 - JS

javascript - 如何使用 ReactJS 将内容复制到剪贴板?

javascript - 带有 JSON 数据的 jquery slider

javascript - dataTables - 仅在选定的行中过滤/搜索

javascript - this.props 'missing' 方法使用来自 react-redux 的连接

javascript - ES6 导出函数的结果

javascript - jQuery:根据动态添加的类选择元素?

javascript - 返回 this 的 ES6 类方法无法由 stderr.on ('data' 调用)

javascript - 如何在不使用扩展运算符的情况下扩展数组?

javascript - 将异步/等待 block 中的部分代码提取到单独的函数中