码迷,mamicode.com
首页 > 其他好文 > 详细

如何为 setTimeout() 方法传参

时间:2016-10-05 13:10:53      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

现有如下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() 方法传参

标签:

原文地址:http://www.cnblogs.com/leon2016/p/5932061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!