手写bind函数

今天无事手写一个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 @   码磊姐姐  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示