window.onload = function() {
var Employee = function(name, bd) {
this.name = name;
this.bd = bd;
this.age = function() {
2017 - this.bd;
}
}
var empName = document.getElementById("name").value;
var empBday = document.getElementById("bday").value;
var empList = new Employee(empName, empBday);
var Btn = document.getElementById('add').addEventListener('click', function() {
console.log(empList);
});
}
<input type="text" id="name" value=""></input>
<input type="text" id="bday" value=""></input>
<button id="add">Add</button>
好吧,即使在我输入一些值之后,我也会 Console.log 名为“emplist”的对象,但我只得到 Employee {name: "", bd: "", age: ƒ}
最佳答案
仅在单击按钮后创建对象:
var Employee = function(name, bd) {
this.name = name;
this.bd = bd;
this.age = function() {
2017 - this.bd;
}
}
window.onload = function () {
document.getElementById('add').addEventListener('click', function(){
var empName = document.getElementById("name").value;
var empBday = document.getElementById("bday").value;
var empList = new Employee(empName, empBday);
console.log(empList);
});
}
关于javascript - 对象即使在赋值后也给出空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45880651/