我正在尝试从过程式JavaScript转向面向对象的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
以获得相同的结果? 最佳答案
我建议您使用基于内置在node.js中的EventEmitter()
对象的事件驱动系统。
为了跟踪状态更改,您可以为状态变量定义一个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);