比较这些与对象相关的简单javascript代码



我已经写了这段代码,任何人都能判断我写的是对是错。

var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
printing: function(){
for (just in employee){
alert(this.emloyee(just)"is"this.employee[just])
}
}
} 

告诉我,上层代码也可以同样工作。

var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert: function(){
alert("Name is " + this.name);
alert("Job is " + this.job);
alert("Age is " + this.age);
}
}
employee.showAlert()

您似乎在寻找

var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert() {
for (const just in this) {
if (typeof this[just] != "function") {
alert(just + " is " + this[just])
}
}
},
};
employee.showAlert()

请注意循环中的const声明、使用属性名称just而不是employee(just)、使用字符串连接+以及使用this而不是employee

此外,showAlert方法本身只是由for … in循环枚举的一个属性,因此我添加了一个条件,只提醒非函数属性。

最新更新