lodash里的内部方法createPartial

68 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第33天,点击查看活动详情

前言

createPartial方法是lodash里的内部方法,可以创建一个包装参数func的函数,用this绑定调用“thisArg”和“partials”的值,并在其接收的参数前面加上前缀。

参数说明:

  • 参数1:函数类型,表示要包装的函数。
  • 参数2:数字类型,表示位掩码标志。
  • 参数3:任意类型,表示'func'的'this'绑定。
  • 参数4:数组类型,表示将参数设置为提供给的参数的前缀。

该方法实现上主要借助createCtor和apply两个内部方法,我们先了解这两个内部方法的实现。

createCtor

在《 lodash里的内部方法createBind 》中我们认识到createCtor方法的实现,createCtor方法会返回新的包装函数。

apply

apply方法是作为原生apply的一种更快的替代方法。

源码如下:

function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

createPartial源码实现

createPartial方法实现上借助apply方法处理this和参数的绑定调用,通过createCtor方法处理函数包装,通过root遍历获取本地this。在 《 关于lodash的内部方法getNative实现 》文章中我们了解了root变量的封装。

实现上通过while循环与初始化的变量赋值调用,最终会返回一个apply调用的闭包。

源码如下:

import apply from './_apply.js';
import createCtor from './_createCtor.js';
import root from './_root.js';

function createPartial(func, bitmask, thisArg, partials) {
  var isBind = bitmask & WRAP_BIND_FLAG,
      Ctor = createCtor(func);
      
  var WRAP_BIND_FLAG = 1;

  function wrapper() {
    var argsIndex = -1,
        argsLength = arguments.length,
        leftIndex = -1,
        leftLength = partials.length,
        args = Array(leftLength + argsLength),
        fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;

    while (++leftIndex < leftLength) {
      args[leftIndex] = partials[leftIndex];
    }
    while (argsLength--) {
      args[leftIndex++] = arguments[++argsIndex];
    }
    return apply(fn, isBind ? thisArg : this, args);
  }
  return wrapper;
}

小结

本篇章我们了解了createPartial内部方法的实现,在实现上通过root变量获取本地全局环境上的方法去跟this作比较,同时我们也了解到apply和createCtor两个内部方法,通过apply去绑定方法和参数,通过createCtor去创建包装函数。