Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - Don't invoke inherited method twice in ES6 classes

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...