单击按钮创建新对象

create new object on button click

本文关键字:对象 新对象 按钮 创建 单击      更新时间:2023-09-26

我是javascript的新手,这完全是为了练习。我有一个html表单(如下(,我希望在单击提交按钮时使用Person构造函数创建一个新对象。我希望新对象的名称是用户的名字。例如,如果名字是john,它将创建一个var john = new Person

形式:

<form name="theform">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    Age: <input type="number" name="age"><br>
    <input type="button" onClick="new Person()" value="Submit">
</form>

施工单位:

function Person(){
    this.firstname = document.theform.fname.value;
    this.lastname = document.theform.lname.value;
    var age = document.theform.age.value;
    this.returnAge = function(){
        return age;
    }
};

只需在提交按钮上添加一个id即可:

document.getElementById("submit").onclick=function(){
    var name=document.forms["theform"]["fname"].value;
    window[name]= new Person();
    console.log(window[name])
}

这没有意义:为什么要动态命名变量?

使用variableName.propertyName引用对象的属性。在这种情况下,这将是personName.firstname这就是存储名字的方式,而不是作为变量名本身(这没有意义:你将如何引用对象?(。

<form name="theform">
    First name: <input id="myName" type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    Age: <input type="number" name="age"><br>
    <input type="button" onclick="window[document.getElementById('myName').value] = new Person();" value="Submit">
</form>

然后,例如,如果打开控制台并搜索john,它将返回对象。

有效,但这样做被认为是糟糕的编码。