向原型函数发送参数

时间:2019-02-05 23:08:06

标签: javascript arrays object prototype

我试图了解如何将原型与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);

2 个答案:

答案 0 :(得分: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上使用此代码

答案 1 :(得分:1)

它可以工作,但是您的代码充满了语法错误。

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