Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is it used for _.once in underscore?

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;
    };
  };
like image 285
Rupert Avatar asked Jan 16 '14 15:01

Rupert


People also ask

What is an underscore in Microsoft Word?

What is an Underscore? Alternatively referred to as a low line, low dash, and understrike, the underscore ( _ ) is a symbol found on the same keyboard key as the hyphen. The picture shows an example of an underscore at the beginning and end of the word "Underscore."

Why do we use underscore characters in C?

- Quora Why is an underscore used in C? It is just like other characters but can be used for following purposes:- 1.Let’s name some identifiers… In the above written identifiers which one you find more readable RHS or LHS ?

What does a blank underscore mean?

A "blank" underscore is often used to indicate that a word or words is missing and n... (more)Loading…. An underscore is simply a line under a word or words, used as emphasis. Also called an underline. On an English-language keyboard, it can be inserted by highlighting a word and pressing CTRL + u.

What is the use of underscore keyword in Java?

What is the use of underscore keyword in Java 9? In earlier versions of Java, the underscore (" _ ") has used as an identifier or to create a variable name. Since Java 9, the underscore character is a reserved keyword and can't be used as an identifier or variable name.


2 Answers

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.

like image 78
allonhadaya Avatar answered Oct 23 '22 05:10

allonhadaya


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

like image 3
Luketep Avatar answered Oct 23 '22 04:10

Luketep