【问题标题】:How to bind to a context if one is passed?如果通过了,如何绑定到上下文?
【发布时间】:2020-06-30 22:29:22
【问题描述】:

我写了这个函数,它基本上模拟了同名的 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;
};

【问题讨论】:

    标签: javascript arrays function iteration bind


    【解决方案1】:

    您可以使用.call 调用具有特定上下文的iteratee

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

    或创建iteratee 函数的永久绑定版本并将其用作已使用的版本。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2014-03-20
      • 2016-10-02
      • 2017-12-28
      相关资源
      最近更新 更多