繁体   English   中英

向原型函数发送参数

[英]Sending an argument to a prototype function

我试图了解如何在 JavaScript 中使用带有对象数组的原型。 我试图通过使用下标向每个 Person 对象发送一个参数,因为我正在考虑使用带有索引的循环。 使用当前代码,我不断收到一条错误消息,指出需要眼镜不是函数。

//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);

您有语法错误。 为了让你的代码工作,它可以定义如下:

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);

此外,您有不必要的if语句。

您可以尝试在JSBin上使用此代码

它有效,但您的代码充满了语法错误。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM