如何为 setTimeout() 方法传参

来源:博客园 分类: 文章浏览史 发布时间:2021-12-05 11:13:41 最后更新:2021-12-05 浏览:288
转载声明:
本文为摘录自“博客园”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2021-12-05 11:13:41

现有如下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.

 

 

 

php技术微信