What is context in _.each(list, iterator, [context])?

前端 未结 5 619
生来不讨喜
生来不讨喜 2020-11-29 16:42

I am new to underscore.js. What is the purpose of [context] in _.each()? How should it be used?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 16:55

    The context lets you provide arguments at call-time, allowing easy customization of generic pre-built helper functions.

    some examples:

    // stock footage:
    function addTo(x){ "use strict"; return x + this; }
    function pluck(x){ "use strict"; return x[this]; }
    function lt(x){ "use strict"; return x < this; }
    
    // production:
    var r = [1,2,3,4,5,6,7,8,9];
    var words = "a man a plan a canal panama".split(" ");
    
    // filtering numbers:
    _.filter(r, lt, 5); // elements less than 5
    _.filter(r, lt, 3); // elements less than 3
    
    // add 100 to the elements:
    _.map(r, addTo, 100);
    
    // encode eggy peggy:
    _.map(words, addTo, "egg").join(" ");
    
    // get length of words:
    _.map(words, pluck, "length"); 
    
    // find words starting with "e" or sooner:
    _.filter(words, lt, "e"); 
    
    // find all words with 3 or more chars:
    _.filter(words, pluck, 2); 
    

    Even from the limited examples, you can see how powerful an "extra argument" can be for creating re-usable code. Instead of making a different callback function for each situation, you can usually adapt a low-level helper. The goal is to have your custom logic bundling a verb and two nouns, with minimal boilerplate.

    Admittedly, arrow functions have eliminated a lot of the "code golf" advantages of generic pure functions, but the semantic and consistency advantages remain.

    I always add "use strict" to helpers to provide native [].map() compatibility when passing primitives. Otherwise, they are coerced into objects, which usually still works, but it's faster and safer to be type-specific.

提交回复
热议问题