Отправка аргумента в функцию-прототип - PullRequest
0 голосов
/ 06 февраля 2019

Я пытаюсь понять, как использовать прототип с массивом объектов в 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 голосов
/ 06 февраля 2019

Это работает, но ваш код был полон синтаксических ошибок.

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);
0 голосов
/ 06 февраля 2019

У вас есть синтаксические ошибки.Чтобы ваш код работал, его можно определить следующим образом:

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

...