I am trying to understand how to use a prototype with an array of objects in JavaScript. I am trying to send an argument to each Person object by using a subscript because I was thinking of using a loop with an index. With the current code I keep getting an error message that needsGlasses is not a function.
//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);
You have syntax errors. To get your code working it may be defined as follows:
function Person (name, age, eyecolor) {
this.name = name;
this.age = age;
this.eyecolor = eyecolor;
}
Person.prototype.needsGlasses= function(boolAnswer){
if (boolAnswer ==1){
console.log("Needs glasses.");
} else {
console.log("Does not need glasses.");
}
}
var peopleArray =
[
new Person ("Abel", 16, "#00f"),
new Person ("Barry", 17, "#A52A2A"),
new Person ("Caine", 18, "#f00"),
];
peopleArray[0].needsGlasses(1);
Furthermore, you have unnecessary if
statements.
You can try to play with this code on JSBin
It works but you code was full of sytax errors.
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."); } else { 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.