_.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;
};
};
看underscore
的throttle
方法发现
var context, args, result;
var timeout = null;
前面几个不显式赋值(即默认为undefined),timeout则赋null值,请问是为什么?
怪我咯2017-04-10 15:27:21
使用var声明变量但未对其加以初始化时,这个变量的值就是undefined,如:
var arr = [];
alert(arr[0] == undefined);//true
而null表示一个空对象指针,用法:
如果定义的变量准备在将来用于保存对象,一般将变量初始化为null(这样做是为了体现null作为空对象指针的惯例)。
题主贴的代码中,var timeout=null是作为定时器使用,初始化为空对象;而前面几个就是正常的变量声明,后面可以直接使用,和null没有什么关系,显式地声明其值为undefined更是没有任何实际意义。