JS中的apply、call、bind方法粗略实现

粗略实现js中的apply、call、bind方法


在开始之前,我们先了解什么是apply、call、bind

[MDN关于call的解释](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call)

作用就是:能够改变函数运行时上下文(ctx),函数在运行时会创建执行上下文中(js代码执行的抽象环境),上下文存在this,vo变量对象,scope-chain作用域链。

注意:this是函数运行时确定的。

使用场景:在一个类数组中,通过call改变运行上下文,转换成数组;

伪代码

	  //使用call改变数组原型方法的this指向
	  const array = Array.prototype.slice.call(arguments);
	  // this总是指向调用它的对象
	  Array.prototype.slice = function(){
	  //此时slice方法中this的值也就是arguments
	  const arr = this;
	  let Array = []
	  for(const i = 0;i<arr.length;i++)
	  //slice通过遍历 返回新数组对象
	  	Array.push(arr[i])
	  }
	  return Array;

示例

function bar(a,b,c){
  const bool =  arguments instanceof Array;//false
  const array = Array.prototype.slice.call(arguments);
  console.log(array) //[1,2,3]
}
bar(1,2,3)
1、call
Function.prototype.myCall = function(self,...args){
   // self 需要绑定的函数执行上下文对象
  self = self !== undefined && self !== null ? Object(self) : window;
   // this指向bar函数,因为this总是指向调用它的对象。
  self.fn = this;
  //执行该方法,接收参数
  const ret = self.fn(...args);
  delete self;
  return ret //返回结果
}
// 例子
function bar(a,b){
  console.log(this) // this: window
  return a+b
}
const a = bar.myCall(null,1,2);// this: Window
console.log(bar.call(null, 1, 2))// this:Window
console.log(a)
2、apply

实现方式与call类似,只是传递的参数是数组

Function.prototype.myApply = function(self,args=[]){
  self = self !== undefined && self !== null ? Object(self) : window;
  self.fn = this;
  const ret = self.fn(...args);
  delete self;
  return ret
}
function bar(a,b) {
  console.log(this)
  return a + b
}
const a = bar.myApply(null, [1, 2]); //this:String {'', fn: ƒ}
console.log(bar.apply(null, [1, 2]))//this: Window
console.log(a)
3、bind
  • bind方法的参数作为新函数的this指向
  • bind方法执行后创建一个新函数,执行新函数得到绑定this后的执行结果
Function.prototype.myBind = function(self){
  self = self !== undefined && self !== null ? Object(self) : window;
  self.fn = this;
  function proxy(...args){
    const ret = self.fn(...args);
    delete self;
    return ret;
  }
  return proxy
}
function bar(a,b) {
  console.log(this)
  return a + b
}
const a = bar.myBind(1)(1,2);// this:Number
console.log(bar.bind(null)(1, 2)) //this: Window
console.log(a)// 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值