我正在努力寻找将传递给函数的所有参数传递给 setTimeout
中的函数的最佳方法。也就是说,在我下面的示例中,我传递了一个参数,但在我看来,随着它变得越来越复杂,它变得丑陋(多个参数)。我希望有一个干净的模式来执行此操作,因为我经常这样做。
onSessionTimeComboChange: function (combo, newValue, oldValue, eOpts) {
var me = this;
me.newValue = newValue;
setTimeout(function () {
var x = me.newValue;
debugger;
}, 100);
}
最佳答案
您无法访问回调中的主要函数变量的原因是 setTimeout()
执行的代码是在单独的执行上下文中运行的调用它的函数。简单来说,回调中的 this
是不一样的。
如果您不想使用提供将回调绑定(bind)到上下文的函数的 Javascript 库(参见 jQuery.proxy 和 underscore.bind ),您将不得不编写自己的非本地 setTimeout
函数来解决这个问题。
这是 web api docs 中提出的解决方案(参见 “这个”问题
部分):
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function () {
vCallback.apply(oThis, aArgs);
} : vCallback, nDelay);
};
如果您不想走那么远,可以改进您的代码,将参数作为 setTimeout
的参数传递给回调:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
检查 JavaScript web api了解更多详情。
所以在你的例子中,你可以这样写:
setTimeout(function (x) {
debugger;
}, 100, newValue);
关于javascript - 想要将函数参数传递到 JavaScript 中的 setTimeout 调用的最佳方式的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18562367/