如何调用一个位于数组中的对象的函数?

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

我遇到了我的程序问题。我试图调用一个函数,该函数是一个数组中的对象的一部分。我无法正常调用该功能。

//Declare Array that will Host Projects
let allProjects = [];

//Create Parent Class that creates objects (Project)
class Project {

constructor(projTitle, projDescription, projHours, projReserved) {

    //Declare variables
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
    this._reserved = projReserved;

    //Send newly constructed object directly to next space in array.
    allProjects.push(this);

    //TODO Reserve function
    function reserve() {
        if (this._reserved === false ) {
            this._reserved === true;
        } else {
            console.log('The project you are trying to reserve has already been taken.');
        }
    }
    };
}

//Call the reserve function of the object in array index 0.
allProjects[0].reserve();

当我运行该程序时,我收到以下错误:

allProjects[0].reserve();
           ^
TypeError: allProjects[0].reserve is not a function

任何帮助和/或提示都会被考虑和赞赏。

javascript debugging
1个回答
2
投票

如果您希望reserve函数在实例化对象上可调用,则应将其放在原型上。此外,===是比较,而不是任务;更改

this._reserved === true;

this._reserved = true;

在全:

class Project {
  constructor(projTitle, projDescription, projHours, projReserved) {
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
    this._reserved = projReserved;

    allProjects.push(this);
  }
  reserve() {
    if (this._reserved === false ) {
      this._reserved = true;
    } else {
      console.log('The project you are trying to reserve has already been taken.');
    }
  }
}

另一个技术上正确但可能效率不高的选项(可能是您最初尝试做的)是将函数分配给构造函数中实例化对象的reserve属性:

class Project {
  constructor(projTitle, projDescription, projHours, projReserved) {
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
    this._reserved = projReserved;

    allProjects.push(this);
    this.reserve = function() {
      if (this._reserved === false ) {
        this._reserved = true;
      } else {
        console.log('The project you are trying to reserve has already been taken.');
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.