[removed] Extend a Function

后端 未结 7 655
小鲜肉
小鲜肉 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:41

    2017+ solution

    The idea of function extensions comes from functional paradigm, which is natively supported since ES6:

    function init(){
        doSomething();
    }
    
    // extend.js
    
    init = (f => u => { f(u)
        doSomethingHereToo();
    })(init);
    
    init();
    

    As per @TJCrowder's concern about stack dump, the browsers handle the situation much better today. If you save this code into test.html and run it, you get

    test.html:3 Uncaught ReferenceError: doSomething is not defined
        at init (test.html:3)
        at test.html:8
        at test.html:12
    

    Line 12: the init call, Line 8: the init extension, Line 3: the undefined doSomething() call.

    Note: Much respect to veteran T.J. Crowder, who kindly answered my question many years ago, when I was a newbie. After the years, I still remember the respectfull attitude and I try to follow the good example.

提交回复
热议问题