標籤:not catch 返回 color contex 控制 cat nbsp sage
function runOnce(fn, context) { //控制讓函數只觸發一次 return function () { try { fn.apply(context || this, arguments); } catch (e) { console.error(e);//一般可以注釋掉這行 } finally { fn = null; } }} // Usage 1:var a = 0;var canOnlyFireOnce = runOnce(function () { a++; console.log(a);}); canOnlyFireOnce(); //1canOnlyFireOnce(); // nothingcanOnlyFireOnce(); // nothing // Usage 2:var name = "張三";var canOnlyFireOnce = runOnce(function () { console.log("你好" + this.name);});canOnlyFireOnce(); //你好張三canOnlyFireOnce(); // nothing // Usage 3:var obj = {name: "天涯孤雁", age: 24};var canOnlyFireOnce = runOnce(function () { console.log("你好" + this.name);}, obj);canOnlyFireOnce(); //你好天canOnlyFireOnce(); // nothing
因為返回函數執行一次後,fn = null
將其設定未null,所以後面就不會執行了。
方法2:
function once(fn, context) { var result; return function() { if(fn) { result = fn.apply(context || this, arguments); fn = null; } return result; };} // Usagevar canOnlyFireOnce = once(function() { console.log(‘Fired!‘);}); canOnlyFireOnce(); // "Fired!"canOnlyFireOnce(); // nothing
只執行一次的js 函數。