从DOM输入元素动态创建现有类的新JS对象实例

问题描述

在HTML的Javascript中,如何创建类的新对象实例,其中该类中新对象的对象名称/变量名称来自输入元素的文本值?

在此示例中... 我有一个名为myClass的类,并且已经创建了一个名为Chickens的myClass对象实例,该实例的属性为'myProperty',其值为100。说我想在浏览器中使用名称输入元素来创建一个新的myClass对象实例,例如狗,并使用属性输入元素将其myProperty值设置为49。

这是我的例子:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <input id="name" placeholder="name">
        <input id="property" placeholder="property">
        <button id="btn"></button>
    </body>
    <script src="rhythm-class.js"></script>
</html>

function myClass() {
        this.myProperty
}

let chickens = new myClass()

chickens.myProperty = '100'

console.log(chickens)

let currObj = null
let currProp = null

document.querySelector('#name').addEventListener('change',(e)=> {
        console.log(e.target.value)
        currObj = e.target.value
        let `${e.target.value}` = new myClass
})
document.querySelector('#property').addEventListener('change',(e)=> {
        console.log(e.target.value)
        currentProp = e.target.value
        let `${currentObj}`.testProperty = e.target.value
})
document.querySelector('#btn').addEventListener('click',()=> {
        console.log(`${currentObj}`.testProperty)
})

解决方法

getIntent
function myClass(value) {
  this.myProperty = value;
}

let chickens = new myClass("100");

console.log(chickens);

let form = document.querySelector("form");
let inputs = form.elements;

form.addEventListener("submit",(e) => {
  e.preventDefault();
  let nameField = inputs["name"];
  let propField = inputs["property"];

  // you can test here if both of the values are set
  window[nameField.value] = new myClass(propField.value);
  console.log(window[nameField.value].myProperty);

});

由于JS中的每个变量都是全局对象的属性,因此我们可以在此处使用它。请注意,全局对象是<!DOCTYPE html> <html> <head> </head> <body> <form> <input id="name" placeholder="name"> <input id="property" placeholder="property"> <button id="btn">Submit</button> </form> </body> </html>。我们将全局对象的属性名称设置为实例名称,然后实例化传递输入值的类。

建议不要使用全局对象,而应使用本地对象来存储变量名。