现有如下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.
时间: 2024-10-17 20:55:42