Javascript Underline.js中的上下文参数做什么?

Javascript Underline.js中的上下文参数做什么?,javascript,underscore.js,Javascript,Underscore.js,可能重复: 因此,在下划线.js中的forEach函数的上下文中: // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.ea

可能重复:

因此,在下划线.js中的forEach函数的上下文中:

// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
  if (obj == null) return;
  if (nativeForEach && obj.forEach === nativeForEach) {
    obj.forEach(iterator, context);
  } else if (obj.length === +obj.length) {
    for (var i = 0, l = obj.length; i < l; i++) {
      if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
    }
  } else {
    for (var key in obj) {
      if (_.has(obj, key)) {
        if (iterator.call(context, obj[key], key, obj) === breaker) return;
      }
    }
  }
};
//基石,一个'each'实现,又称'forEach'。
//使用内置的“forEach”、数组和原始对象处理对象。
//委派到**ECMAScript 5**的本机“forEach”(如果可用)。
var each=u0.each=0.forEach=函数(对象、迭代器、上下文){
if(obj==null)返回;
if(nativeForEach&&obj.forEach===nativeForEach){
forEach(迭代器,上下文);
}否则如果(对象长度===+对象长度){
对于(变量i=0,l=obj.length;i

什么是参数上下文以及如何使用它?

设置传递的迭代器函数的
值(调用上下文)

iterator.call(context, obj[i], i, obj);
      //         ^---right here
JavaScript的
.call
.apply
方法允许您调用函数,并将所调用函数的
this
值设置为您提供的第一个参数

所以如果我这样做

var obj = {foo:"bar"};
func.call(obj);
…在
func
this
的值将是
{foo:“bar”}
对象


因此,如果您提供了该参数,则下划线将其用作调用上述传递的函数时调用
.call的第一个参数。

我在实践中理解这一点,但仍然发现下划线源代码有点混乱。基于code
iterator.call(context,obj[i],i,obj)
我发现不清楚当没有传递
context
时会发生什么。如果没有
context
存在,我是否缺少将
context
设置为
obj
的条件?@I_得出结论:不,没有这样的条件。如果未提供
上下文
,则它将是
未定义的
,这意味着函数中
的值将是全局对象(如果不是在严格模式下),或者
未定义的
(如果是在严格模式下)。