码磊姐姐
雄关漫道真如铁,而今迈步从头越。

今天无事手写一个bind函数

//重写bind函数
Function.prototype.bindDemo = function(){
  // arguments可以获取到传的参数
  // 1.先把获取到的数据转换为数组的格式
  let args = Array.prototype.slice.call(arguments);
  // 2.获取数组中第一个元素,即this即将指向的数据
  let first = args.shift();
 // 3.获取要改变this指向的数据的this,这里的this指的是fn1的this,因为fn1会调用这个bindDemo函数
  let self = this;
  return function(){
  return self.apply(first,args);
}
}
//调用bind函数改变函数fn1的this指向
function fn1(a,b,c){
console.log('fn1 this',this)//打印fn1的this,验证
return 'this is fn1'
}
let target = {x:100,b:200}
let fn2 = fn1.bindDemo(target,1,2,3);//将fn1的this指向为target;
fn2();

可以看到fn1的this指向已经是target了!!

posted on 2024-04-26 17:49  码磊姐姐  阅读(6)  评论(0编辑  收藏  举报