Created
September 8, 2012 08:38
-
-
Save bxt/3672815 to your computer and use it in GitHub Desktop.
JavaScript の once よくつかうので (I actually don't use it that often)
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
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_; | |
} |
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
// 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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.