单击按钮创建新对象
create new object on button click
我是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
,它将返回对象。
有效,但这样做被认为是糟糕的编码。
相关文章:
- 查找关键字并创建新对象
- 创建新对象时,为什么要更新旧对象
- 为什么要使用立即调用的函数来创建新对象
- 剑道网格-插入具有外部列的新对象失败
- 将原型调用为新对象中的另一个原型
- 将新对象添加到本地存储
- $$hashKey在Angular中push()新对象时未生成新值
- 从分析类传递现有对象,否则创建一个新对象
- 为什么这个功能打印“;未定义的未定义的“;作为联系人名称,添加“新对象”
- Will my'新对象'在套接字断开连接时被垃圾收集
- 从数组javascript创建新对象
- 为新对象添加函数,将对象添加到数组中.理解困难'这'关键字
- 在for循环-Javascript中创建新对象
- Javascript:使用一个预先存在的对象值作为一个新对象的键
- 确定是创建新对象还是更新现有对象
- 返回它在Javascript中构建的新对象
- 如何使用Typescript创建一个包含对象的字段的新对象
- Sinon:存根和整个对象,并将其替换为新对象
- JavaScript:创建新对象类型的方法
- 将新对象“附加”到 ng 重复项