javascript - 在 JS 中“动态”调用一个函数,例如
问题描述
解决方案
// Class and its functions
function myClass() {
this.existingProperty = 5;
}
myClass.prototype.myFunction = function () {
this.resultProperty = this.newProperty + this.existingProperty;
}
myClass.prototype.myFunction2 = function () {
this.resultProperty = this.newProperty * this.existingProperty;
}
// Memory
const locoParentis = {};
let nameField;
// Name of object instance of myClass (for example: type dogs into the brower/HTML "name" input)
document.querySelector('#name').addEventListener('change', (e)=>{
nameField = e.target.value;
})
// Add the new objeect instance to the array (for example: click add new object to create an object called dogs with an existingProperty of 5)
document.querySelector('#new').addEventListener('click', ()=>{
locoParentis[nameField] = new myClass();
console.log(locoParentis);
})
// Create/set new property in object instance (for example: typing 9 in the property value input sets dogs' newProperty to 9)
document.querySelector('#property').addEventListener('input', (e)=>{
locoParentis[nameField].newProperty = Number(e.target.value);
console.log(locoParentis);
})
document.querySelector('#functions').addEventListener('change', (e)=>{
// you can check here for undefined
locoParentis[nameField][e.target.value]();
console.log(locoParentis[nameField].resultProperty);
})
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" placeholder="name">
<button id="new">add new object</button>
<br>
<input id="property" placeholder="property value">
<select id="functions">
<option>apply a function</option>
<option value="myFunction">sum</option>
<option value="myFunction2">multiply</option>
</select>
</body>
</html>
试试这个。
但是有一些事情需要考虑。您不需要添加单独的“添加新对象”按钮。当您选择是求和还是乘法时,可以创建一个新实例。
推荐阅读
- html - Bootstrap“拉右”类没有按预期工作
- amazon-web-services - 如何在任务定义中为运行在 AWS ECS 上的 mosquitto-eclipse 配置健康检查?
- arrays - 如何多次列出数组中多个值的总和并找到最常见的输出?
- python - 带有电子生成器的 python-shell 在我的计算机上工作正常,但在其他计算机上不工作
- r - R:循环一个序列并将其放入单独的列表中
- github - PySpark:如何将 GitHub 库导入 Databricks?
- django - Django - 密码验证帮助文本翻译
- node.js - 无法使用 mongoose 连接到 mongodb atlas
- vb.net - Visual Studio 在使用 Crystal 报表时抛出 System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A5023'
- php - pChart 在主机服务器上工作,但在 XAMPP 上工作:未捕获的错误:不能将字符串偏移量用作数组