首页 > 解决方案 > Javascript Setter 不是函数错误

问题描述

当我尝试在控制台上记录 isCheckedOut 设置器时,出现错误 testLib.isCheckedOut is not a function

我很难弄清楚为什么。任何帮助都会非常好

            /* Parent Class */
class Library {
  constructor(title) {
    this._title = title;
    this._isCheckedOut = false;
    this._ratings = [];
  }

  get title() {
    return this._title;
  }

  get isCheckedOut() {
    return this._isCheckedOut;
  }

  set isCheckedOut(value) {
    this._isCheckedOut = value;
  }

  get ratings() {
    return this._ratings;
  }

  getAverageRating() {

  }

  toggleCheckOutStatus() {

  }

  addRating() {

  }
}

const testLib = new Library;
console.log(testLib.isCheckedOut(true));

标签: javascriptclasssetter

解决方案


Setters obfuscate the fact that they're functions to callers. When you have an object with a setter, to invoke the setter, assign to the property:

someObj.theSetterPropertyName = theArgumentToPassToSetter;

Similarly, to invoke a getter, reference the property as an expression:

someObj.theGetterPropertyName

So, you want:

class Library {
  constructor(title) {
    this._title = title;
    this._isCheckedOut = false;
    this._ratings = [];
  }

  get title() {
    return this._title;
  }

  get isCheckedOut() {
    return this._isCheckedOut;
  }

  set isCheckedOut(value) {
    this._isCheckedOut = value;
  }

  get ratings() {
    return this._ratings;
  }
}

const testLib = new Library;
testLib.isCheckedOut = true; // invoke setter
console.log(testLib.isCheckedOut); // invoke getter


推荐阅读