Created
September 28, 2016 00:28
-
-
Save jacks0n/ed44fb514278230407aed35c4f32ae8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Execute a function only once per instance. | |
* | |
* @param {...*} arguments | |
* | |
* @return {*} | |
* The return value of the function's first execution. | |
*/ | |
Function.prototype.once = function() { | |
var _self = this, | |
args = arguments; | |
return function() { | |
if (!this.hasRun) { | |
this.result = _self.apply(_self, args); | |
this.hasRun = true; | |
} | |
return this.result; | |
}(); | |
}; | |
// Usage | |
// var foo = function() { console.log('foo!'); }; | |
// foo.once(); // Prints 'foo!' | |
// foo.once(); // Doesn't print anything. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment