setTimeout callback argument

前端 未结 4 1589
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 22:20

Let\'s consider this piece of JavaScript:

function Person(name) {
    this.name = name;
}

Person.prototype.showName = function() {
    alert(this.name);
}

         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 23:05

    If the accepted answer is just too long to read:

    setTimeout(mike.showName(), 5000);
    

    This will execute whatever mike.showName() returns after 5,000 milliseconds.

    setTimeout(function(){ mike.showName(); }, 5000);
    

    This will execute anonymous function after 5000 milliseconds that calls mike.showName() , the actual function.

    Another way to achieve same effect:

    setTimeout(mike.showName.bind(mike), 5000);
    

提交回复
热议问题