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实现 #107

Open
louzhedong opened this issue Dec 13, 2018 · 0 comments
Open

bind实现 #107

louzhedong opened this issue Dec 13, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

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;
}
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