JavaScript一次函数

Every so often you have a function which you only want to run once.  Oftentimes these functions are in the form of event listeners which may be difficult to manage.  Of course if they were easy to manage, you'd just remove the listeners but that's a perfect world and sometimes you simply want the ability to only allow a function to be called once.  Here's the JavaScript function to make that possible!

通常,您都有一个只想运行一次的功能。 这些功能通常以事件侦听器的形式出现,可能难以管理。 当然,如果它们易于管理,您只需删除监听器即可,但这是一个完美的世界,有时您只是希望仅允许一次调用一个函数的功能。 这是JavaScript函数,使之成为可能!

JavaScript (The JavaScript)

Think of this once function as a wrapper for the function you provide:

将该函数视为您提供的函数的包装器:


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


The wrapping function is fired only once because a tracker variable is used to ensure the function is only executed once.  Many JavaScript toolkits offer this as a feature but the code to accomplish this feat is so small that it's good to have available in the case that you can dodge a JavaScript toolkit!

包装函数仅触发一次,因为使用了跟踪器变量以确保该函数仅执行一次。 许多JavaScript工具箱都将此功能作为功能提供,但是实现这一壮举的代码非常小,以至于在可以躲避JavaScript工具箱的情况下最好使用它!

翻译自: https://davidwalsh.name/javascript-once

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值