[removed] Extend a Function

后端 未结 7 654
小鲜肉
小鲜肉 2020-11-30 17:47

The main reason why I want it is that I want to extend my initialize function.

Something like this:

// main.js

window.onload = init();
function init         


        
7条回答
  •  鱼传尺愫
    2020-11-30 18:43

    This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.

    First let us extend javascript function.

    function Base(props) {
        const _props = props
        this.getProps = () => _props
    
        // We can make method private by not binding it to this object. 
        // Hence it is not exposed when we return this.
        const privateMethod = () => "do internal stuff" 
    
        return this
    }
    

    You can extend this function by creating child function in following way

    function Child(props) {
        const parent = Base(props)
        this.getMessage = () => `Message is ${parent.getProps()}`;
    
        // You can remove the line below to extend as in private inheritance, 
        // not exposing parent function properties and method.
        this.prototype = parent
        return this
    }
    

    Now you can use Child function as follows,

    let childObject = Child("Secret Message")
    console.log(childObject.getMessage())     // logs "Message is Secret Message"
    console.log(childObject.getProps())       // logs "Secret Message"
    

    We can also create Javascript Function by extending Javascript classes, like this.

    class BaseClass {
        constructor(props) {
            this.props = props
            // You can remove the line below to make getProps method private. 
            // As it will not be binded to this, but let it be
            this.getProps = this.getProps.bind(this)
        }
    
        getProps() {
            return this.props
        }
    }
    

    Let us extend this class with Child function like this,

    function Child(props) {
        let parent = new BaseClass(props)
        const getMessage = () => `Message is ${parent.getProps()}`;
        return { ...parent, getMessage} // I have used spread operator. 
    }
    

    Again you can use Child function as follows to get similar result,

    let childObject = Child("Secret Message")
    console.log(childObject.getMessage())     // logs "Message is Secret Message"
    console.log(childObject.getProps())       // logs "Secret Message"
    

    Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.

提交回复
热议问题