function once(fn, context) { 
	var result;

	return function() { 
		if(fn) {
			result = fn.apply(context || this, arguments);
			fn = null;
		}

		return result;
	};
}

// Usage
var canOnlyFireOnce = once(function() {
	console.log(\'Fired!\');
});

canOnlyFireOnce(); // \"Fired!\"
canOnlyFireOnce(); // nada

这个 once 函数能够保证你提供的函数只执行唯一的一次,防止重复执行。

收藏 打印