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的实现 #10

Open
dvlin-dev opened this issue Apr 4, 2022 · 0 comments
Open

模拟bind的实现 #10

dvlin-dev opened this issue Apr 4, 2022 · 0 comments
Labels
js JavaScript

Comments

@dvlin-dev
Copy link
Owner

API

function.bind(thisArg[, arg1[, arg2[, ...]]])
返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。

  1. 对于普通函数,绑定this指向
  2. 对于构造函数,要保证原函数的原型对象上的属性不能丢失
Function.prototype.mybind = function (context, ...args) {
  if (typeof this !== 'function') {
    throw new Error("this is not a function")
  }
  let self = this
  let FB = function () {
    self.apply(
      //当为普通函数的时候 this 指向window,self指向绑定函数 为 false,this为绑定的实例对象
      //当为构造函数的时候 this 指向实例,self指向绑定函数 为 true,this为new出来的实例对象
      this instanceof self ? this : context,
      args.concat(Array.prototype.slice.call(arguments))
    )
  }
  FB.prototype = Object.create(this.prototype)
  return FB
}
@dvlin-dev dvlin-dev added the js JavaScript label Apr 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant