前言:
今天给大家带来手写 bind 函数,希望对大家有所帮助!
代码:
注意点:
- 需要返回一个函数
- 返回的函数 需要考虑 是不是 new
- 不是 new 需要 使用 apply 或者 call 指定 this
Function.prototype.myBind = function(context){
if (typeof this !== 'function') {
throw new TypeError('Type Error !')
}
var _this = this;
var args = [...arguments].slice(1);
return function F(){
if (this instanceof F) {
// 判断是不是 直接 new 此函数
return new _this(...args,...arguments);
}
return _this.apply(context,args.concat(...arguments))
}
}
var show = function(){
console.log(this.name);
console.log(...arguments);
}
let c = {
name:'wjf'
}
show.myBind(c,1,2,3)(4,5,6)
// wjf
// 1 2 3 4 5 6