相关疑难解决方法(0)

将正确的"this"上下文传递给setTimeout回调?

如何将上下文传递给setTimeout?我想打电话this.tip.destroy(),如果this.options.destroyOnHide在1000毫秒.我怎样才能做到这一点?

if (this.options.destroyOnHide) {
     setTimeout(function() { this.tip.destroy() }, 1000);
} 
Run Code Online (Sandbox Code Playgroud)

当我尝试以上时,this指的是窗口.

javascript callback this settimeout

226
推荐指数
4
解决办法
17万
查看次数

如何使用"setTimeout"来调用对象本身

为什么我不能setTimeout在javascript对象中使用?

Message = function () {

    ...
    ...        

    this.messageFactory = ...
    this.feedbackTag = document.getElementById('feedbackMessages');

    this.addInfo = function (message) {
        var info = this.messageFactory.createInfo(message); // create a div
        this.feedbackTag.appendChild(info);

        setTimeout('this.feedbackTag.removeChild(info)', 5000);
        // why in here, it complain this.feedbacktag is undefined ??????

    };
}
Run Code Online (Sandbox Code Playgroud)

感谢Steve的解决方案,现在如果代码如下所示它将起作用...因为之前'this'实际指向setTimeOut中的函数,它不能重新发送消息.

Message = function () {

    ...
    ...        

    this.messageFactory = ...
    this.feedbackTag = document.getElementById('feedbackMessages');

    this.addInfo = function (message) {
        var info = this.messageFactory.createInfo(message); // create a div
        this.feedbackTag.appendChild(info);

        var _this = this;
        setTimeout(function() { _this.feedbackTag.removeChild(info); }, …
Run Code Online (Sandbox Code Playgroud)

javascript settimeout

24
推荐指数
2
解决办法
4万
查看次数

标签 统计

javascript ×2

settimeout ×2

callback ×1

this ×1