简体   繁体   中英

Javascript - How to implement override-able lifecycle hooks

I am creating a class which I expect to be extended. This class allows customization of functionality using override-able lifecycle hooks (similar to React.js components). In the base class these methods do nothing.

What is the "right" way of coding this?

Should I not implement these in the base class and do a check for if the methods exists, for example:

class BaseClass {
    //...
    runLifeCycle() {
        if (this.lifeCycleMethodA) this.lifeCycleMethodA()
    }
    //...
}

Or should I implement them as empty functions in the base class?

class BaseClass {
    //...
    runLifeCycle() {
        this.lifeCycleMethodA()
    }

    lifeCycleMethodA() {
        // empty block
    }
    //...
}

What is the cleaner approach?

It's really up to you, there's no "right" way. Some inputs:

  • If you expect the subclass methods not to call the base class methods (as with React's lifecycle methods), leaving them out is fine.

  • If you expect the subclass methods to call the base class methods, then supplying them makes that simpler for the subclass (they don't need a guard).

  • If you expect the base class to be used directly, rather than subclassed, often, supplying them with no-op behavior makes it simpler for the code calling the methods (it doesn't need a guard).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM