让你弄懂 call、apply、bind的应用和区别
发布时间:2020-12-14 04:42:51 所属栏目:大数据 来源:网络整理
导读:call、apply、bind使用和区别 // 有只猫叫小黑,小黑会吃鱼 const cat = { name: ‘小黑‘ ,eatFish(...args) { console.log( ‘this指向=‘, this ); console.log( ‘...args‘ ,args); console.log( this .name + ‘吃鱼‘ ); },} // 有只狗叫大毛,大毛会
call、apply、bind使用和区别// 有只猫叫小黑,小黑会吃鱼 const cat = { name: ‘小黑‘,eatFish(...args) { console.log(‘this指向=>‘,this); console.log(‘...args‘,args); console.log(this.name + ‘吃鱼‘); },} // 有只狗叫大毛,大毛会吃骨头 const dog = { name: ‘大毛‘,eatBone(...args) { console.log(‘this指向=>‘,args); console.log(this.name + ‘吃骨头‘); },} console.log(‘=================== call =========================‘); // 有一天大毛想吃鱼了,可是它不知道怎么吃。怎么办?小黑说我吃的时候喂你吃 cat.eatFish.call(dog,‘汪汪汪‘,‘call‘) // 大毛为了表示感谢,决定下次吃骨头的时候也喂小黑吃 dog.eatBone.call(cat,‘喵喵喵‘,‘call‘) console.log(‘=================== apply =========================‘); cat.eatFish.apply(dog,[‘汪汪汪‘,‘apply‘]) dog.eatBone.apply(cat,[‘喵喵喵‘,‘apply‘]) console.log(‘=================== bind =========================‘); // 有一天他们觉得每次吃的时候再喂太麻烦了。干脆直接教对方怎么吃 const test1 = cat.eatFish.bind(dog,‘bind‘) const test2 = dog.eatBone.bind(cat,‘bind‘) test1() test2() 详见文章 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |