search

Home  >  Q&A  >  body text

underscore - JavaScript 未声明的变量需要显式赋null吗?

 _.throttle = function(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

underscorethrottle方法发现

var context, args, result;
var timeout = null;

前面几个不显式赋值(即默认为undefined),timeout则赋null值,请问是为什么?

PHPzPHPz2903 days ago375

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-10 15:27:21

    使用var声明变量但未对其加以初始化时,这个变量的值就是undefined,如:
    var arr = [];
    alert(arr[0] == undefined);//true

    而null表示一个空对象指针,用法:
    如果定义的变量准备在将来用于保存对象,一般将变量初始化为null(这样做是为了体现null作为空对象指针的惯例)。

    题主贴的代码中,var timeout=null是作为定时器使用,初始化为空对象;而前面几个就是正常的变量声明,后面可以直接使用,和null没有什么关系,显式地声明其值为undefined更是没有任何实际意义。

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 15:27:21

    他这里在上面声明,是为了下面两个function里使用和控制这几个变量

    reply
    0
  • Cancelreply