[英]Sending an argument to a prototype function
I am trying to understand how to use a prototype with an array of objects in JavaScript.我试图了解如何在 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.
我试图通过使用下标向每个 Person 对象发送一个参数,因为我正在考虑使用带有索引的循环。 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.此外,您有不必要的
if
语句。
You can try to play with this code on JSBin您可以尝试在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.