0

这是一个常见的习惯用法,通过 undescore 封装到一个函数中

_.each(obj1, function(val, key, context, obj2){
});

回调中第四个参数的目的是什么 - obj2。这是一个正在循环的对象,因此它应该始终在外部范围内可用,如obj1.

是否有一个示例说明您需要obj1通过obj2.

我试图理解obj2是为了什么。这是代码的确切行 - 第 83 行。

if (iterator.call(context, obj[i], i, obj) === breaker) return;
4

2 回答 2

4

如果您将命名函数的引用作为回调传递,则obj1可能不可用:

function my_callback(val, key, context, obj2) {
    ...
}

function do_stuff() {
    var obj1 = ...
    _.each(obj1, my_callback);
}
于 2013-05-02T18:08:39.410 回答
1

What is the purpose of the 4th argument in the callback - obj2. This is the object one is looping through so it should always be available in the outer scope as obj1.

It's so you can reuse the same function for looping through multiple objects, and still have access to the object being iterated within the function. The function you use might well be define elsewhere. You could have a library of functions you use for various iteration purposes. It's rare to want to know what the object is (hence it being so far into the argument list), but there are use cases.

于 2013-05-02T18:12:48.697 回答