javascript anonymous function parameter passing

后端 未结 5 533
终归单人心
终归单人心 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:07

    The anonymous function has access to me because it is declared inside of the outer function (the toggle function); it is closed over by the outer function.

    Your handler function will be called by setInterval, which passes exactly zero arguments. This means you can't use parameters in the handler function itself.

    I you really want to pass me explicitly, you could write a function accepting an parameter, and have that function return an anonymous function without parameters, but which could access the creator function's parameter:

    toggle: function() {
        var me = this;
        var handler = (function (o) { return function() { o.progress() }; })(me);
        me.intervalId = setInterval(handler, me.intervalTime);
        //...More code
    }
    

    But this basically adds a layer of redirection without really making it more legible. Unless you pull that creating function outside:

    function createProgressHandler(o) {
        return function() {
            o.progress();
        };
    }
    
    // ...
    
    toggle: function() {
        var me = this;
        var handler = createProgressHandler(me);
        me.intervalId = setInterval(handler, me.intervalTime);
        //...More code
    }
    

提交回复
热议问题