发送参数传递给函数原型

问题描述 投票:-2回答:2

我想了解如何使用原型对象在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);
javascript arrays object prototype
2个回答
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
投票

它的工作原理,但你的代码是充满语法错误的。

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);
© www.soinside.com 2019 - 2024. All rights reserved.