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

apply,call,bind的实现 #75

Open
gdutwyg opened this issue Oct 15, 2019 · 0 comments
Open

apply,call,bind的实现 #75

gdutwyg opened this issue Oct 15, 2019 · 0 comments
Labels

Comments

@gdutwyg
Copy link
Owner

gdutwyg commented Oct 15, 2019

  • apply和call就是传参不一样,apply传数组,call就是正常传参,但是两个都是会在调用的时候同时执行调用的函数。
  • bind则会返回一个绑定了this的函数.不会执行调用的函数。
// apply
Function.prototype.selfApply = function (context, args) {
  context  = context || window
  args = args ? args : []
  const key = Symbol()
  context[key] = this // 此时的this 就是调用的selfApply的function
  const res = cotext[key](...args)
  delete context[key]
  return res
}
// call 相对 apply的区别就是参数可以任意
// ...args 转成数组args
Function.prototype.selfCall = function (context, ...args) {
  context  = context || window
  args = args ? args : []
  const key = Symbol()
  context[key] = this // 此时的this 就是调用的selfCall的function
  const res = cotext[key](...args)
  delete context[key]
  return res
}
// bind
Function.prototype.myBind = function (context, args) {
  context  = context || window
  args = args ? args : []
  const fn = this // 此时的this 就是调用的myBind的function
  return function newFn(...newArgs) {
    // 要考虑要返回的函数可能会调用new ,这里要判断是否要调用
    if(this instanceof newFn) {
      return new fn(...args, ...newArgs)
    }
    return fn.apply(context, [...args, ...newArgs])
  }
}

参考

面试感悟,手写bind,apply,call

@gdutwyg gdutwyg changed the title bind,apply,call的实现 apply,call,bind的实现 Oct 16, 2019
@gdutwyg gdutwyg added the js label Oct 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant