Javascript:无法调用getter

Hel*_*osy 1 javascript getter-setter

class Clock {
    constructor() {
        this.schedule = [];
        this.simulationTime = 0;
    }

    get isEmpty() {
      return this.schedule == false;
    }

    popFirstItem(){
      if(isEmpty){
        throw "error";
      }
    }
};  
Run Code Online (Sandbox Code Playgroud)

我希望isEmpty()popFirstItem()方法中调用getter .但是,我无法做到.什么是调用的正确方法isEmpty()popFirstItem()方法是什么?

Ank*_*wal 5

你需要使用this.isEmpty.该this总会引用类和使用的参考,你可以调用类的方法或属性:

class Clock {
    constructor() {
        this.schedule = [];
        this.simulationTime = 0;
    }

    get isEmpty() {
      console.log('Inside isEmpty()');
      return this.schedule == false;
    }

    popFirstItem(){
      if(this.isEmpty){
        throw "error";
      }
    }
};  
var clock = new Clock();
console.log(clock.popFirstItem());
Run Code Online (Sandbox Code Playgroud)