手写call,apply,bind函数

98 阅读1分钟

call - 改变了this执行,让新的对象可以执行该函数。 \

     Function.prototype.Mycall=function(context){
     context=context||window;
     context.fn=this;            // this指向调用call的对象,即我们要改变this指向的函数
     const args = [...arguments].slice(1)   //执行当前函数
     const result =context.fn(...agres)     //删除我们声明的fn属性
     deletre context  fn
     return result
     }

实现分析

  • 首先context为可选参数,如果不传的话默认上下文是window
  • 接下来给content创建一个fn属性,并将值设置为需要调用的函数
  • 因为call可以传入多个参数作为调用函数的参数,所有需要将参数剥离出来
  • 然后调用函数并将对象上的函数删除

apply apply和call实现类似,不同的就是参数的处理

Function.prototype.Mybind=function(context){
if (typeof this !== 'function') { throw new TypeError('Error') }
     context=context||window;
     context.fn=this;            // this指向调用call的对象,即我们要改变this指向的函数
 if (arguments[1]) { 
 result = context.fn(...arguments[1])
 } 
 else { 
 result =context.fn()
 }
     deletre context  fn
     return result
 }
 
 

### bind 因为bind转换后的函数可以作为构造函数使用,此时this应该指向构造出的实例,而不是bind绑定的第一个参数

 Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
    throw new TypeError('Error')
}
//返回一个绑定this的函数,这里我们需要保存this
const _this = this
const args = [...arguments].slice(1)
    //返回一个函数
return function F() {
    //因为返回一个函数,我们可以new F()需要判断能当做构造函数吗
    if (this instanceof F) {
        return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
}

}