相关疑难解决方法(0)

如何使用"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万
查看次数

函数声明或函数表达式

我在块范围中定义函数时遇到了问题.考虑以下程序:

try {
    greet();

    function greet() {
        alert("Merry Christmas!");
    }
} catch (error) {
    alert(error);
}
Run Code Online (Sandbox Code Playgroud)

我希望这个程序能够提醒Merry Christmas!.但是在Firefox中给了我以下内容ReferenceError:

ReferenceError: greet is not defined
Run Code Online (Sandbox Code Playgroud)

在Opera和Chrome上,它会像我预期的那样提醒问候语.

显然,Firefox会将块范围内的功能视为一段FunctionExpression时间,而Opera和Chrome将其视为一个FunctionDeclaration.

我的问题是为什么Firefox表现不同?哪种实现更符合逻辑?哪一个符合标准?

我理解JavaScript中的声明是悬而未决的,因此如果在同一范围内的两个或多个不同的块中声明相同的函数,那么就会出现名称冲突.

但是,每次声明函数时重新声明函数都不是更合乎逻辑,这样你就可以做到这样的事情:

greet(); // Merry Christmas!

function greet() {
    alert("Merry Christmas!");
}

greet(); // Happy New Year!

function greet() {
    alert("Happy New Year!");
}
Run Code Online (Sandbox Code Playgroud)

我认为除了解决上面描述的块范围问题之外,这将非常有用.

javascript scope function-declaration function-expression

6
推荐指数
1
解决办法
185
查看次数

setTimeout()在自调用函数中的递归函数

我想将我的代码分发为一个自我唤起的匿名函数,正如我看到许多人所做的那样.此外,在我的代码中,我必须监视另一个lib加载,所以我可以在它可用时使用它.

(function(window, document, undefined) {
  staffHappens();
  var initMyLib = function() {
    if (typeof(myLib) == 'undefined') {
      setTimeout("initMyLib()", 50);
    } else {
      useMyLib();
    }
  }
  moreStaffHappens();
  initMyLib(); //-> initMyLib is undefined
})(this, document);
Run Code Online (Sandbox Code Playgroud)

这个错误怎么会发生?initMyLib应该在封闭(自我调用)函数的范围内吗?

javascript closures anonymous-function settimeout

5
推荐指数
1
解决办法
1万
查看次数