如何调用与数组中包含的对象分开的函数?

时间:2018-09-01 22:47:44

标签: javascript debugging

我的程序遇到问题。我试图调用一个函数,该函数是放置在数组中的对象的一部分。我在正确调用该函数时遇到麻烦。

//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

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

1 个答案:

答案 0 :(得分: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.');
      }
    }
  }
}