call/apply/bind的实现

一:手写函数实现call的功能,但是可能一些边界情况没有考虑完整

复制代码
 1 Function.prototype.hycall = function(thisArg, ...arg) {
 2     // 这里的this指向调用这个hycall的函数
 3     var fn = this
 4         //判断thisArg是否为空,是的话赋值为window(因为调用call如果第一个参数为null或者undefined,this指向window) Object的作用是把括号里面的东西转换成为一个对象,以免输入类型为数值无法给它赋fn
 5     thisArg = thisArg ? Object(thisArg) : window
 6     thisArg.fn = fn
 7     var result = thisArg.fn(...arg)
补充 delete thisArg.fn
8 return result 9 } 10 11 function abc(num1, num2) { 12 console.log(this); 13 result = num1 + num2 14 console.log(result); 15 } 16 // console.log(Object(0)); 17 abc.call('hello', 10, 20) 18 abc.hycall('hello', 10, 20)
复制代码

调用结果一致

简单思路就是 把调用call的函数赋值给thisArg 然后调用 返回结果即可

需要考虑的情况

1:call会自动把0转换成为一个Number对象,我们这里就需要利用到Object(thisArg)来实现

2:如果接收到的第一个参数是null,或者undefined,所以我们需要对thisAgr进行一个判断,如果有这些情况把它赋值成为window

二:手写函数实现apply的功能

复制代码
 1 Function.prototype.hyapply = function(thisArg, argArray) {
 2     var fn = this
 3     thisArg = thisArg ? Object(thisArg) : window
 4     thisArg.fn = fn
 5     argArray = argArray ? argArray : []
 6     var result = thisArg.fn(...argArray)
 7     delete thisArg.fn
 8     return result
 9 }
10 
11 function abc(num1, num2) {
12     console.log(this);
13     result = num1 + num2
14     console.log(result);
15 }
16 abc.apply('hello', [10, 20])
17 abc.hyapply('hello', [10, 20])
复制代码

apply需要考虑的地方:

1:和call一样,使用Object()

2:需要判断传进来的数组是否为空,为空的话赋值一个新数组

三·手写函数实现bind的功能

bind与前面两个不同的是,函数调用bind会返回一个新的函数 并且bind传参的方式也不一样 引用bind的时候可以传参,引用bind构造的新函数也可以传参

1 function abc(num1, num2) {
2     console.log(this);
3     result = num1 + num2
4     console.log(result);
5 
6 }
7 var heihei = abc.bind('hello', 20)
8 heihei(10)

输出结果为30 利用function proxyFn来构造新函数 参数可以在最终调用的时候用finalarg来合并

代码:

复制代码
 1 Function.prototype.hybind = function(thisArg, ...argArray) {
 2     var fn = this
 3     thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
 4 
 5     function proxyFn(...arg) {
 6         thisArg.fn = fn
 7         var finalarg = [...argArray, ...arg]
 8         var result = thisArg.fn(...finalarg)
 9         delete thisArg.fn
10         return result
11     }
12     return proxyFn
13 }
14 
15 function abc(num1, num2) {
16     console.log(this);
17     result = num1 + num2
18     console.log(result);
19 
20 }
21 var heihei = abc.bind('hello', 20)
22 var heiheihy = abc.hybind('hello', 20)
23 heihei(10)
24 heiheihy(10)
复制代码

实现:关键就在于利用this来转变

 

posted @   沁霓  阅读(90)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示