bind
函数的实现比call
和apply
这两个函数要略复杂一些,因为bind
需要返回一个函数,要判断一些边界问题。
以下就是bind
的实现:
Function.prototype.myBind = function(context) { if (typeof context === undefined || typeof context === null) { context = window } const _this = this const args = [...arguments].slice(1) // 返回一个函数 return function F() { // 因为返回了一个函数, 我们可以 new F(), 所以需要判断 if (this instanceof F) { return new _this(...args, ...arguments) } // 这边的 apply 严谨点可以自己实现 return _this.apply(context, args.concat(...arguments)) } }
bind
返回了一个函数,对于函数来说有两种方式调用,一种是直接调用,一种是通过new
的方式。
对于直接调用,这里选择了apply
的方式实现,但是对于参数需要注意以下情况:因为bind
可以实现类似这样的代码f.bind(obj, 1)(2)
,所以我们需要将参数拼接一下,于是就有了args.concat(...arguments)
再来说一下通过new
的方式,对于new
的情况,不会被任何方式改变this
,所以对于这种情况我们需要忽略传入的this
。