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

JavaScript -- 模拟实现bind #18

Open
mt51 opened this issue Oct 27, 2018 · 0 comments
Open

JavaScript -- 模拟实现bind #18

mt51 opened this issue Oct 27, 2018 · 0 comments

Comments

@mt51
Copy link
Owner

mt51 commented Oct 27, 2018

模拟实现bind方法

先来分析一下,我们自定义bind方法需要实现哪些功能

  1. 返回一个新的绑定函数
  2. 调用返回的绑定函数的时候可以传入参数修改this的指向
  3. 返回的绑定函数可以使用new操作符调用,此时需要忽略传入的this参数

1、第一个版本,返回一个绑定函数并且能够修改this的指向

Function.prototype._bind = function (context) {
    var args = Array.prototype.slice.call(arguments, 1)
    var self = this
    return function () {
        args = args.concat(Arary.prototype.slice.call(arguments))
        self.apply(context, args)
    }
}
// 测试
function foo () {
    console.log(this.a)
}
var a = 'global'
var obj = {
    a: 'local'
}
var bar = foo._bind(obj)
bar() // 'local'

2、第二个版本,处理通过new调用返回的绑定函数

Function.prototype._bind = function (context) {
    if (typeof this !== 'function') {
        throw Error('Function.prototype._bind - what is trying to be bound is not callable')
    }
    var args = Array.prototype.slice.call(arguments, 1)
    var self = this
    function Tmp () {}
    function Fbind () {
        args = args.concat(Array.prototype.slice.call(arguments))
        self.apply(this instanceof Tmp ? this : context, args)
    }
    Tmp.prototype = this.prototype
    Fbind.prototype = new Tmp()
    return Fbind
}

参考

MDN bind

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