Skip to content

Instantly share code, notes, and snippets.

@bxt
Created September 8, 2012 08:38
Show Gist options
  • Save bxt/3672815 to your computer and use it in GitHub Desktop.
Save bxt/3672815 to your computer and use it in GitHub Desktop.
JavaScript の once よくつかうので (I actually don't use it that often)
function once (fn) {
var done = false, result;
function _once_ () {
if(!done) {
result = fn.apply(this,Array.prototype.slice.call(arguments))
done = true;
}
return result;
}
return _once_;
}
// Test object style:
function TestObject(prop) {
this.setProp = function(newProp) {
prop = newProp;
return prop;
}
this.getProp = function() {
return prop;
}
}
(function(){
var t = new TestObject(5);
console.log('getProp start',t.getProp());
t.setPropOnce = once(t.setProp);
console.log('setPropOnce(11) first time',t.setPropOnce(11));
console.log('setPropOnce(13) second time',t.setPropOnce(13));
console.log('getProp end',t.getProp());
})();
console.log('-----------');
// Test functional style:
(function(){
var x = 0;
function t(y) {
x += y;
return x;
}
var tOnce = once(t);
console.log('x start',x);
console.log('tOnce(3) first time',tOnce(3));
console.log('tOnce(5) second time',tOnce(5));
console.log('x end',x);
})();
@bxt
Copy link
Author

bxt commented Sep 11, 2012

See also the same function in underscore.js https://github.com/documentcloud/underscore/blob/3b023262ce795083fa37777f4846209cc7fe33e7/underscore.js#L630
They clear the function reference after calling it once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment