admin管理员组文章数量:1220960
I just look at the once API of source in underscore.js, then wandering what is it the used for in the method, it seems doing nothing:
func = null
the source:
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
I just look at the once API of source in underscore.js, then wandering what is it the used for in the method, it seems doing nothing:
func = null
the source:
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
Share
Improve this question
asked Jan 16, 2014 at 15:35
RupertRupert
5395 silver badges9 bronze badges
2
|
4 Answers
Reset to default 14What the function does can be found in the documentation:
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.
Why set func = null
is explained in this commit message:
Assuming we'll never run the wrapped function again on _.once(), we can assign null to the
func
variable, so function (and all its inherited scopes) may be collected by GC if needed.
From the official underscorejs website:
once _.once(function)
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.
http://underscorejs.org/#once
It's unclear if you are asking about the entire function or just the func = null
line. If the latter, see just step 3, below.
ran
is initially false.
When you run the returned function for the first time:
ran
is set totrue
- the function passed into
once
is called - the function reference is deleted (presumably to aid garbage collection)
memo
is returned
When you run the returned function again (since ran
is now true
):
memo
is returned
Also worth pointing out is that the memo
will hold the result of the initially executed function.
So when you call your function again, it will not be executed but the result of the first call will be returned.
本文标签: javascriptwhat is it used for once in underscoreStack Overflow
版权声明:本文标题:javascript - what is it used for _.once in underscore? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739247217a2154743.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
func = null
is done? – thefourtheye Commented Jan 16, 2014 at 15:36