Skip to content

bind实现 #107

Open
Open
@louzhedong

Description

Function.prototype.bind2 = function (ctx) {

  if (typeof this !== 'function') {   // 去除不是函数调用bind的情况
    throw new Error('Function.prototype.bind - what is trying to be bound is not callable"');
  }
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1);  // 调用bind函数时传入的参数,可以传入一部分参数

  var fNULL = function () { };

  var fBind = function () {
    var bindArgs = Array.prototype.slice.call(arguments);   // bind完后的函数传入的参数
    return self.apply(this instanceof fBind ? this : ctx, args.concat(bindArgs));  // 把两次传入的参数合并成一个数组,调用apply
  }

  fNULL.prototype = this.prototype;  // fNull函数的目的是将this的prototype和fBind的prototype断开,否则当修改一个的时候,另一个也会被修改
  fBind.prototype = new fNULL();
  return fBind;
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions