如何正确地使用和为 setTimeout() 方法传参

原创 javascirpt

现有如下 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,那么应该如何传参数呢?

匿名函数

第一个参数为匿名函数。

setTimeout(function () {
  console.log(apple, "is a kind of healthy fruit");
}, 5000);

Function.prototype.bind()

setTimeout(printApple.bind(null, apple), 5000);

设置可选参数

第三个参数作为 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.

如果觉得这对你有用,请随意赞赏,给与作者支持
评论 0
最新评论