setInterval, this, again

前端 未结 5 1477
故里飘歌
故里飘歌 2021-01-27 16:32

I have a problem in regard to setInterval that I can\'t figure out.

There is the problem with the scope when calling setInterval or timeout fro

5条回答
  •  佛祖请我去吃肉
    2021-01-27 17:15

    This is your problem simplified to bare bones:

    var ship = {
        name: 'Sheep',
        ding: function() {
            console.log(this.name);
        }
    }
    
    setTimeout(ship.ding, 1000); // doesn't work correctly
    

    It may help to see another example to understand why the above doesn't work:

    var ding = ship.ding;
    ding(); // doesn't work either
    

    In JavaScript this depends on how you call your function. ship.ding() will set this to the sheep object. Bare ding() call will set this to the window object.

    You can bind the function to the object you want by using .bind() method. (Function.prototype.bind())

    var ding = ship.ding.bind(ship);
    ding(); // works
    

    ding is now permanently bound to the sheep object. You can use exactly the same approach with setTimeout:

    setTimeout(ship.ding.bind(ship), 1000);
    

提交回复
热议问题