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