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

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


答案 1

The context parameter just sets the value of in the iterator function.this

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of , which is represented by since we passed it as the context parameter.someOtherArraythis

If you do not set the context, then will refer to the object.thiswindow


Extras:

To answer the upvoted question found in the comments below, let's move the anonymous callback into a function for easy re-use:What's the advantage of that? Why not just refer to someOtherArray[num] rather than this[num]?iteratee

const someOtherArray  = ["name","patrick","d","w"];
const yetAnotherArray = ["what","goes","here","?"];

function alertStr(num){
    alert( this[num] );
}

_.each([1, 2, 3], alertStr, someOtherArray);
_.each([1, 2, 3], alertStr, yetAnotherArray);

You can see how the reference allows us to re-use the function across multiple calls with different values. This would not work if we had the hardcoded inside the .thisiteratee_.eachcontextsomeOtherArrayiteratee


答案 2

context is where refers to in your iterator function. For example:this

var person = {};
person.friends = {
  name1: true,
  name2: false,
  name3: true,
  name4: true
};

_.each(['name4', 'name2'], function(name){
  // this refers to the friends property of the person object
  alert(this[name]);
}, person.friends);