javascript anonymous function parameter passing

后端 未结 5 532
终归单人心
终归单人心 2021-02-02 13:04

I have some javascript code (within an object) :

toggle: function() {
    var me = this;
    var handler = function() { me.progress() };
    me.intervalId = setI         


        
5条回答
  •  醉梦人生
    2021-02-02 13:14

    The reason

    var handler = (function(o) { o.progress();})(this));
    

    doesn't work because it just immediately calls the anon function, therefore immediately calling o.progress() and assigns the return value of the anon function (undefined) to handler. You need to return an actual function from the outer function:

    handler = (function(me){
        return function(){
            return me.progress();
        }
    }(this));
    

    On the flip side this is equivalent and just as bad looking as bad looking as the variable assignment (but can still be useful, particularly if this needs to be done in a loop, with the changing i rather than the fixed this).


    BTW, if the progress function doesn't have any calls to this inside it , just doing handler = this.progress (without the parens) might suffice.

提交回复
热议问题