如果一个通过,如何绑定到上下文?

How to bind to a context if one is passed?

我写了这个函数,它基本上模拟了同名的 Underscore.js 函数。一切正常,除了我正在努力理解如何在通过时绑定到上下文。我确定我应该使用 function.prototype.bind(),但我不确定具体如何实施它。

// _.each(collection, iteratee, [context])
// Iterates over a collection of elements (i.e. array or object),
// yielding each in turn to an iteratee function, that is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// Returns the collection for chaining.

_.each = function (collection, iteratee, context) {
  
  if(Array.isArray(collection)){
    for(let i = 0; i < collection.length; i++){
      iteratee(collection[i], i, collection);
    };
  };

  if(typeof collection === 'object' && !Array.isArray(collection)){
    Object.entries(collection).map(([key, value]) => {
      iteratee(value, key, collection);
    });
  };

  return collection;
};

您可以使用 .call 在特定上下文中调用 iteratee

iteratee.call(context, value, key, collection);

或创建 iteratee 函数的永久绑定版本,并按其已使用的方式使用它。

iteratee = iteratee.bind(context);
// calls to iteratee(...) will always have `this` as `context`