javascript - 动态创建设置器?
问题描述
有没有办法像这样动态地将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>
我只需要它来编写类,这些类可以动态地为其属性创建设置器。
解决方案
你可以这样做:
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]
}
}
}
推荐阅读
- python - cv2.imshow() 在循环中打开多个窗口
- javascript - 用户成功通过不和谐 Oauth 后如何运行文件?
- sqlite - 在数据库 sqlite3 中查询
- php - $_(美元下划线)变量是什么意思?
- javascript - 在 Ionic 5 中使用 Ionic Animation 的页面转换
- laravel - 当我启动 laravel echo 服务器时出现错误?
- python - 如何更改我的 seaborn catplot 中的数量或行数和列数
- linux - 获取具有高 I/O 读取请求的文件名
- python - 有没有一种简单的方法可以列出使用 python 中的 FHIR 包存在的所有 FHIR 资源?
- javascript - 由于 MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff)而被阻止