首页 > 解决方案 > 动态创建设置器?

问题描述

有没有办法像这样动态地将setter添加到对象?

output = document.querySelector(".output")
log = (out)=>{
  output.innerHTML = out
}

class A {
  constructor(some){
    this._some = some
  }    
}

myObj = new A(1)
// myObj = Add setter there...
<div class="output"></div>  

我只需要它来编写类,这些类可以动态地为其属性创建设置器。

标签: javascriptnode.js

解决方案


你可以这样做:

class A {
  constructor(some){
    this[some] = some // This needs to be a string, otherwise it doesn't work
  }    
}

如果您需要做更复杂的事情,您可以执行以下操作:

const exampleInput = {
  prop1: 123,
  prop2: "someString"
}

class A {
  // Make some an object like the one above
  constructor(some){
    for (prop in some) {
       this[prop] = some[prop]
    }
  }    
}

for...in 循环的解释


推荐阅读