Skip to content

Instantly share code, notes, and snippets.

@jacks0n
Created September 28, 2016 00:28
Show Gist options
  • Save jacks0n/ed44fb514278230407aed35c4f32ae8b to your computer and use it in GitHub Desktop.
Save jacks0n/ed44fb514278230407aed35c4f32ae8b to your computer and use it in GitHub Desktop.
/**
* 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