Don't invoke inherited method twice in ES6 classes

一曲冷凌霜 提交于 2019-12-12 06:49:10

问题


I'm moving from RequireJS to browserify (together with babelify) and try to rewrite my current modules to classes. For each of my RequireJS modules I have a method called eventHandler which handles all module specific events. Now when I extend a class, the parent class calls the subclass`s eventHandler method which leads to invoking the method twice.

Parent class:

'use strict';

class Tooltip {
    constructor() {
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
    }
}

module.exports = Tooltip;

Subclass:

'use strict';

import Tooltip  from './Tooltip';

class Block extends Tooltip {
    constructor() {
        super();
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
        // Gets called twice
    }
}

module.exports = Block;

I liked the fact that the eventHandler method was named the same across all modules as it was easier to maintain. That's why I'd like to keep this pattern. So what would be the best way to solve this problem? Thanks for any suggestions!


回答1:


Since you know the parent constructor calls this.eventHandler, don't do so in the derived classes:

'use strict';

import Tooltip  from './Tooltip';

class Block extends Tooltip {
    constructor() {
        super();
        // (No call here)
    }

    eventHandler() {
        // Module specific events
        // Gets called twice
    }
}

module.exports = Block;

Re your comment:

The parent classes don't always implement an eventHandler method. So I need to ensure it gets called in this case as well.

Where they do, don't do the call. Where they don't, do do the call. Subclasses are very tightly bound to superclasses, by their nature.

If you can assume (!) that the presence of eventHandler in the super means it has called it from its constructor, you could do something like this:

constructor() {
    super();
    if (!super.eventHandler) {
        this.eventHandler();
    }
}

...but again, the nature of the super/sub relationship is that it's very tightly-bound, so relying on your knowledge of whether the super does this or not is reasonable.



来源:https://stackoverflow.com/questions/33981728/dont-invoke-inherited-method-twice-in-es6-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!