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
  • 1 You want to know about the method, or why func = null is done? – thefourtheye Commented Jan 16, 2014 at 15:36
  • 3 Have you checked the documentation?? – Pointy Commented Jan 16, 2014 at 15:36
Add a comment  | 

4 Answers 4

Reset to default 14

What 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:

  1. ran is set to true
  2. the function passed into once is called
  3. the function reference is deleted (presumably to aid garbage collection)
  4. memo is returned

When you run the returned function again (since ran is now true):

  1. 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