Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bind实现 #21

Open
MyPrototypeWhat opened this issue Mar 22, 2022 · 0 comments
Open

Bind实现 #21

MyPrototypeWhat opened this issue Mar 22, 2022 · 0 comments

Comments

@MyPrototypeWhat
Copy link
Owner

MyPrototypeWhat commented Mar 22, 2022

bind

  • function-bind.js

    module.exports = Function.bind || function bind(that /* , ...args */) {
      // 判断是否是一个函数
      var F = aCallable(this);
      var Prototype = F.prototype;
      // 拿到除that之外的函数
      var partArgs = arraySlice(arguments, 1);
      // 返回的函数
      var boundFunction = function bound(/* args... */) {
        // 拼接参数
        var args = concat(partArgs, arraySlice(arguments));
        // 重点!!
        // 判断this是否是boundFunction的实例
        // 函数bind之后的函数再new出一个实例,这个实例其实是通过,原函数new出的实例,并不会更改this指向
        return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
      };
      // 继承this函数的原型
      if (isObject(Prototype)) boundFunction.prototype = Prototype;
      return boundFunction;
    };
    var construct = function (C, argsLength, args) {
      if (!hasOwn(factories, argsLength)) {
        for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
        // 通过Function创建函数
        // 创建出的函数为
        // ƒ anonymous(C,a
        // ) {
        // return new C(a[0],a[1])
        // }
        factories[argsLength] = Function('C,a', 'return new C(' + join(list, ',') + ')');
      } return factories[argsLength](C, args);
    };
  • 例子

    function a(){}
    function b(){}
    const c=a._bind(b)
    const d=new c('a','c','d')
    • da函数bind之后的函数new出的实例对象

    • construct函数返回出的函数为

      ƒ anonymous(C,a) {
        // C是通过boundFunction闭包保存的例子中的a函数
        return new C(a[0],a[1],a[2])
      }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant