美好的一天, 我的问题可能有点'新手',但我是! 我有一个像这样的对象:
var person = {
firstName: null,
lastName: null,
age: null,
eyeColor: null
};
所以,当我点击一个按钮来“添加”一个新人(一个新对象)时,我希望有这样的东西......
$("p").click(function(){
var newPerson = new Person("John", "Doe", "50", "blue");
console.log("A new person has been created!");
});
但是这个场景对一个对象有好处......如何创建具有不同参数的“多个”新人,特别是不同的对象名称(var newPerson)? 我知道我可以有一个带参数的函数,但是对象的名称保持不变,所以对象被新的替换... 我希望我很清楚......或者至少有人会理解我!谢谢! :)
答案 0 :(得分:0)
当您使用具有相同标签的var
关键字时,它会切换您所引用的对象,因此问题是找到存储People类实例的位置而不是创建不同的变量名。这样的事情可以奏效:
var people = [];
$("p").click(function(){
var newPerson = new Person("John", "Doe", "50", "blue");
people.push(newPerson);
console.log("A new person has been created!");
});
通过这种方式,您可以使用其people
数组中存储的索引来引用不同的人。
console.log(people[0]) //-> {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"}
希望这有帮助!
答案 1 :(得分:-1)
我想这可以帮助您解决问题:
HTML PART:
<form method="POST" id="form">
<input id="name" placeholder="First name"></input><br>
<input id="lname" placeholder="Last name"></input><br>
<input id="age" placeholder="Age"></input><br>
<input id="eye" placeholder="Eye Color"></input><br>
<button type="submit" id="btn">CREATE</button>
</form>
JS PART:
function person(f_name, l_name, age, eye_c) {
this.fname = f_name;
this.lname = l_name;
this.age = age;
this.eyec = eye_c;
} // Defining the object, consider it like a object template.
person.prototype.notif = function () {
alert("The user with name " + this.fname + " logged in!");
} // Here is a function added outside the object, does not need to be done this way...It pops an alert box.
var id = 0; // ...so we can track the id/number of submits.
var list = []; // Here we will put all the entries, objects.
document.getElementById("form").onsubmit = function(event) {
event.preventDefault();
var name_value = document.getElementById("name").value; // Taking the value from the input field.
var lname_value = document.getElementById("lname").value; // Taking the value from the input field.
var age_value = document.getElementById("age").value; // Taking the value from the input field.
var eye_value = document.getElementById("eye").value; // Taking the value from the input field.
list[id] = new person(name_value, lname_value, age_value, eye_value); // Making the new object of name list with an ID ( list0, list1... )
list[id].notif(); // Giving the notification...
id++; // Increasing the ID afther every submit, so we can track the list.
console.log(list);
}; // Creating the new object (could be new acc for example), with the entered parameters.