简体   繁体   English

在setTimeout中使用对象文字函数

[英]Use of object literal function inside setTimeout

im having some code similar to this: 我有一些与此类似的代码:

var options = {
    timerInterval: 800,
    timer: null
};

var functions = {
    someFunction: function() {

    }
};

options.timer = setTimeout('functions.someFunction()', options.timerInterval);

This won't fire though, because it can't find the functions object. 但是,这不会触发,因为找不到函数对象。

What to do? 该怎么办? :D :d

try this: 尝试这个:

options.timer = setTimeout(function () {
  functions.someFunction()
}, options.timerInterval)

it's not recommended to write your function argument as a string in a setTimeout b/c it has to do some conversions that adds overhead to your script and can be avoided by using an anonymous function to call your function. 不建议在setTimeout b / c中将函数参数写为字符串,它必须进行一些转换,这会增加脚本的开销,并且可以通过使用匿名函数来调用函数来避免这种情况。

You can do this: 你可以这样做:

options.timer = setTimeout(functions.someFunction, options.timerInterval);

But... the more robust way to do it is like this: 但是...更强大的方法是这样的:

options.timer = setTimeout(function () {
    functions.someFunction();
}, options.timerInterval);

The second version is better because in JavaScript, the special variable this is dynamically scoped, which means that it will take the value from the scope it is evaluated in, not the scope it was defined in. Do a google search for "understanding javascript this" to find out more. 第二个版本更好,因为在JavaScript中, this是动态范围内的特殊变量,这意味着它将从被评估的范围(而不是其定义的范围)中获取值。Google搜索“了解javascript this” “ 了解更多。

On a related note, ES5 introduces Function.prototype.bind to deal with this problem. this相关的是,ES5引入了Function.prototype.bind来处理this问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM