根据 JavaScript 类 中的状态变化采取更好的方法

Better method for acting upon state change in JavaScript classes

我正在尝试从面向过程转向面向对象JavaScript,但我遇到了一个问题,我确信有答案,但我无法解决。

目前,我的每个方法都会检查 属性 的状态,然后根据该状态执行操作。我宁愿做的是更新状态,并且这些方法作为状态更改的结果执行。这可能吗,还是我没抓住要点?

这是我目前拥有的:

class ClassExample {
    constructor({state = false} = {}) {
        this.state = state;
        ...
    }

    aMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }

    bMethod() {
        if(this.state) {
            //Do something
            this.state = false;
        } else {
            //Do something else
            this.state = true;
        }
    }
}

并且:

const myObject = new ClassExample();
myObject.aMethod();
myObject.bMethod();

鉴于这两种方法都检查相同的 属性,这会导致大量冗余 if 语句。有没有更好的方法来组织此 class 以获得相同的结果?

我建议您使用基于 EventEmitter() 对象内置于 node.js 的事件驱动系统。

要跟踪状态变化,您可以为状态变量定义一个 setter,这样只要有人设置新状态,您的 setter 函数就会被调用,然后它可以触发指示状态已更改的事件。同时,对象之外的对象中的任何人都可以为状态更改注册事件侦听器。

这是一个简短的例子:

const EventEmitter = require('events');

class ClassExample extends EventEmitter {
    constructor(state = 0) {
        super();
        // declare private state variable
        let internalState = state;
        // define setter and getter for private state variable
        Object.defineProperty(this, "state", {
            get: function() {
                return internalState;
            },
            set: function(val) {
                if (internalState !== val) {
                    internalState = val;
                    // send out notification 
                    this.emit("stateChanged", val);
                }
            }
        });
    }
}

let e = new ClassExample(1);
console.log(e.state);

e.on("stateChanged", function(newVal) {
    console.log("state has changed to ", newVal);
});

e.state = 3;
console.log(e.state);