如何让 ES6 类方法在调用子类函数时执行一些默认行为,而不使用超级构造函数?

因此,在尝试构建一些 js 类时,我遇到了一些知识差距,因为这是我第一次实现 OOP 和 ES6 构造函数。


我基本上有一个运行一个respond()方法的应用程序,当在"Emergency Event".


在此示例中,无论子类方法中声明了什么,派生自的所有子类都NuclearStrategy应该始终如此。如果那么除了 之外什么都不应该做。Appease the populationActionrespondToThreat()eventIsJustTest === trueAppease the population


这就是我正在实施的:


class NuclearStrategy {

  constructor(props) {

    this.eventOrigin = props.eventOrigin;

  }


  appeaseAllPopulation() {

    console.log('✅ Appeasing the population');

  }


  respondToThreat({ eventIsJustTest }) {

    this.appeaseAllPopulation();

    if (eventIsJustTest) return;                            // I expect this to exit the function and ignore anything declared after <super.respondToThreat()>

  }

}



class Action extends NuclearStrategy {

  constructor(props) {

    super(props)

  }


  respondToThreat(responseArgs) {

    super.respondToThreat(responseArgs.eventIsJustTest);   // <- I can't have this in my code

    console.log(`✅ Playing alert siren`);                 // <- This shouldn't be executed

    console.log(`✅ Launched ICBM nuke to enemy`)          // <- Avoid also

  }

}



new Action({ eventOrigin: 'East Qorea' }).respondToThreat({ eventIsJustTest: true });

这执行


✅ Appeasing the population

✅ Playing alert siren

✅ Launched ICBM nuke to enemy

应该只执行


✅ Appeasing the population

Action.respondToThreat这样,即使警报只是针对(RIP Earth) ,我也无法阻止核武器发射nuclear test。另外,我不能super在我的子类中进行任何调用super.respondToThreat(),该appeaseAllPopulation()行为应该默认执行,而无需调用它。


您对这个应用程序有什么建议吗?先感谢您。



aluckdog
浏览 165回答 2
2回答

红糖糍粑

一个简单的解决方案是根本不重写respondToThreat,而是调用应由子类实现的方法/挂钩。class NuclearStrategy {&nbsp; constructor(props) {&nbsp; &nbsp; this.eventOrigin = props.eventOrigin;&nbsp; }&nbsp; appeaseAllPopulation() {&nbsp; &nbsp; console.log('Broadcasting ');&nbsp; }&nbsp; respondToThreat({ eventIsJustTest }) {&nbsp; &nbsp; console.log(`✅ Appeasing the population`);&nbsp; &nbsp; if (eventIsJustTest) return;&nbsp; &nbsp; this.respondToNonTestThreat();&nbsp; }&nbsp;&nbsp;&nbsp; respondToNonTestThreat() {} // default implementation do nothing}class Action extends NuclearStrategy {&nbsp; respondToNonTestThreat() {&nbsp; &nbsp; console.log(`✅ Playing alert siren`);&nbsp; &nbsp; console.log(`✅ Launched ICBM nuke to enemy`);&nbsp; }}const action = new Action({ eventOrigin: 'East Qorea' });console.log("test threat:");action.respondToThreat({ eventIsJustTest: true });console.log("non-test threat:");action.respondToThreat({});

守候你守候我

如果您想防止程序员重写重要方法,您可以只传递要执行的逻辑,而不是子类化。在这种情况下,调用逻辑的类应该记录在什么情况下执行什么逻辑。传递的参数是什么以及期望的返回值应该是什么。上面的内容可以通过很多不同的方式来完成,下面是一个例子:class Hooks {&nbsp; constructor(hooks, context) {&nbsp; &nbsp; this.hooks&nbsp; &nbsp;= hooks;&nbsp; &nbsp; this.context = context;&nbsp; }&nbsp;&nbsp;&nbsp; find(...path) {&nbsp; &nbsp; let cursor = this.hooks;&nbsp; &nbsp; for (const key of path) {&nbsp; &nbsp; &nbsp; if (!cursor[key]) return this.noop;&nbsp; &nbsp; &nbsp; cursor = cursor[key];&nbsp; &nbsp; }&nbsp; &nbsp; return cursor.bind(this.context);&nbsp; }&nbsp;&nbsp;&nbsp; noop() {}}class NuclearStrategy {&nbsp; static withPresetHooks(hooks) {&nbsp; &nbsp; return (props) => new this({ ...props, hooks });&nbsp; }&nbsp; constructor(props) {&nbsp; &nbsp; this.eventOrigin = props.eventOrigin;&nbsp; &nbsp; this.hooks&nbsp; &nbsp; &nbsp; &nbsp;= new Hooks(props.hooks || {}, this);&nbsp; }&nbsp; appeaseAllPopulation() {&nbsp; &nbsp; console.log('Broadcasting ');&nbsp; }&nbsp; respondToThreat({ eventIsJustTest }) {&nbsp; &nbsp; console.log(`✅ Appeasing the population`);&nbsp; &nbsp; this.hooks.find("respondToThreat", "eventIsJustTest", !!eventIsJustTest)();&nbsp; }}const createAction = NuclearStrategy.withPresetHooks({&nbsp; respondToThreat: {&nbsp; &nbsp; eventIsJustTest: {&nbsp; &nbsp; &nbsp; true: function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log(`✅ Testing alert siren`);&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; false: function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log(`✅ Playing alert siren`);&nbsp; &nbsp; &nbsp; &nbsp; console.log(`✅ Launched ICBM nuke to enemy`);&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; },&nbsp; },});const action = createAction({ eventOrigin: 'East Qorea' });console.log("test threat:");action.respondToThreat({ eventIsJustTest: true });console.log("non-test threat:");action.respondToThreat({});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript