【发布时间】:2019-02-05 23:08:06
【问题描述】:
我试图了解如何在 JavaScript 中使用带有对象数组的原型。我试图通过使用下标向每个 Person 对象发送一个参数,因为我正在考虑使用带有索引的循环。使用当前代码,我不断收到一条错误消息,即 needsGlasses 不是函数。
//class constructor
function Person (name, age, eyecolor) {
this.name = name;
this.age = age;
this.eyecolor = eyecolor;
}
//array of Person objects
var peopleArray =
[
new Person ("Abel", 16, blue),
new Person ("Barry", 17, brown),
new Person "Caine", 18, green),
];
//prototype
Person.prototype.needsGlasses=function(boolAnswer){
if (boolAnswer ==1){
console.log("Needs glasses.");
}
if (boolAnswer !=1){
console.log("Does not need glasses.");
}
}
//when I try to send a '1' or '0' to an object in the array, I get an error.
peopleArray[0].needsGlasses(1);
【问题讨论】:
-
只要我修复了
peopleArray中的语法错误,这段代码就可以正常运行并返回预期的结果。 -
@Kai — 没必要这样做
-
您需要提供minimal reproducible example。您的代码会抛出与您声称的错误不同的错误。
-
if (boolAnswer ==1) {} if (boolAnswer !=1) {} :)
标签: javascript arrays object prototype