Any anonymous function will change "this" to point to window, so you will lose your object reference.
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何为 setTimeout() 方法传参相关的知识,希望对你有一定的参考价值。
现有如下javascript代码:
function printApple(apple){
console.log(apple, "is a kind of healthy fruit");
}
var apple = "apple";
setTimeout("printApple(apple)", 5000);
则在执行setTimeout时,会报 apple is not defined,那么应该如何传参数呢?
1、 匿名函数
setTimeout(function(){
console.log(apple, "is a kind of healthy fruit");
}, 5000);
2、Function.prototype.bind()
setTimeout(printApple.bind(null, apple), 5000);
3、第三个参数作为 setTimeout() 内部函数的参数,其实setTimeout()可以接受多个参数:setTimeout(yourFunctionReference, 5000, param1, param2, paramN);
var apple = "apple";
setTimeout(printApple, 5000, apple);
由于IE10以前的版本,不支持为setTimeout()和setInterval()方法传递第三个参数,所以在IE10以前的版本使用时,要添加以下代码:
if (document.all && !window.setTimeout.isPolyfill) {
var __nativeST__ = window.setTimeout;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function () {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
window.setTimeout.isPolyfill = true;
}
if (document.all && !window.setInterval.isPolyfill) {
var __nativeSI__ = window.setInterval;
window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeSI__(vCallback instanceof Function ? function () {
vCallback.apply(null, aArgs);
} : vCallback, nDelay);
};
window.setInterval.isPolyfill = true;
}
Any anonymous function will change "this" to point to window, so you will lose your object reference.
以上是关于如何为 setTimeout() 方法传参的主要内容,如果未能解决你的问题,请参考以下文章
如何为数组中的每个项目评估包含 settimeout 的函数(Javascript)
Solr Highlighting:如何为同一字段请求多个片段长度?