【问题标题】:Sending an argument to a prototype function向原型函数发送参数
【发布时间】:2019-02-05 23:08:06
【问题描述】:

我试图了解如何在 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);

【问题讨论】:

  • 只要我修复了peopleArray 中的语法错误,这段代码就可以正常运行并返回预期的结果。
  • @Kai — 没必要这样做
  • 您需要提供minimal reproducible example。您的代码会抛出与您声称的错误不同的错误。
  • if (boolAnswer ==1) {} if (boolAnswer !=1) {} :)

标签: javascript arrays object prototype


【解决方案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上使用此代码

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多