Changing the scope of an anonymous function to setTimeout causes a strange warning

it interested me solely as research and personal development. I have a set of functions / variables with names.

within one function I need to call another via setTimeout, but the scope will be 'this'. I'm struggling a bit with this, can't tie it to when setTimeout starts.

var foo = {
    ads: ["foo","bar"],
    timeDelay: 3,
    loadAds: function() {
        var al = this.ads.length;
            if (!al)
                return; // no ads

            for(var i = 0; i < al; i++) {
                setTimeout(function() {
                    this.scrollAd(this.ads[i]);
                }.apply(this), this.timeDelay * 1000);
            }
        },
        scrollAd: function(adBlock) {
            console.log(adBlock);

        }
    };
};

.apply (this) CHANGES the scope since console.log displays the right object back, but it runs the function immediately, and then a warning / warning appears when the callback remains empty:

useless setTimeout call (missing quotes around argument?)

Is there an elegant way to do this at all? i know i can do

var _this = this;

and a link _thisin the announcer callback. for example, in mootools I would use .bind(this)instead ...

, , " " , ...

+3
2
for(var i = 0; i < al; i++) {
    setTimeout(function() {
        this.scrollAd(this.ads[i]);
    }.apply(this), this.timeDelay * 1000);
}

apply , . , , (undefined) setTimeout, .

, , this, ( , ):

for(var i = 0; i < al; i++) {
    setTimeout(function(that, j) {
        return function() {
            that.scrollAd(that.ads[j]);
        };
    }(this, i), this.timeDelay * 1000);
}

ECMAScript Fifth Edition, :

for (var i= 0; i<al; i++)
    setTimeout(this.scrollAd.bind(this, this.ads[i]), this.timeDelay*1000);

( function.bind , .)

+9

, , - :

var self = this;
setTimeout(function(){self.scrollAd(ad);}, this.timeDelay * 1000);

.apply(), :

var self = this;
setTimeout(function(){
    function(){
    }.apply(self);
}, this.timeDelay * 1000);

, for i , , i (.. i == al). , i .

, , :

var foo = {
    ads: ["foo","bar"],
    timeDelay: 3,
    loadAds: function() {
        function runTimed(o, fn, args, time)
        {
            setTimeout(function(){ fn.apply(o, args); }, time);
        }
        var al = this.ads.length;
            if (!al)
                return; // no ads

            for(var i = 0; i < al; i++) {
                runTimed(this, this.scrollAd, this.ads[i], this.timeDelay*1000);
            }
        },
        scrollAd: function(adBlock) {
            console.log(adBlock);
        }
    };
};

: , .

, , scrollAd (i ).

+2

Source: https://habr.com/ru/post/1722774/


All Articles