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的方法的模拟 #3

Open
shen-zhao opened this issue Apr 20, 2021 · 0 comments
Open

bind的方法的模拟 #3

shen-zhao opened this issue Apr 20, 2021 · 0 comments
Labels

Comments

@shen-zhao
Copy link
Owner

shen-zhao commented Apr 20, 2021

bind API MDN

// 最简版
function bind(fn, context) {
  return function () {
    return fn.apply(context, Array.prototype.slice.call(arguments))
  }
}

// 预置参数
function bind(fn, context) {
  var args = Array.prototype.slice.call(arguments, 2)
  return function () {
    return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)))
  }
}

// new操作符,忽略thisArg
function bind(fn, context) {
  var argsPre = Array.prototype.slice.call(arguments, 2)
  function bindFn() {
    context = this instanceof bindFn ? this : context
    const args = argsPre.concat(Array.prototype.slice.call(arguments))
    return fn.apply(context || null, args)
  }
  bindFn.prototype = fn.prototype
  return bindFn
}

// new优化版,不修改原函数的原型对象
function bind(fn, context) {
  var argsPre = Array.prototype.slice.call(arguments, 2)
  function Fake(){}

  function bindFn() {
    context = this instanceof bindFn ? this : context
    const args = argsPre.concat(Array.prototype.slice.call(arguments))
    return fn.apply(context || null, args)
  }
  Fake.prototype = fn.prototype
  bindFn.prototype = new Fake
  return bindFn
}
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