js中call、apply和bind方法的简单实现

1.call方法的实现

Function.prototype.hycall = function (thisArg, ...nums) {
    // 1.获取所要执行的函数
    let fn = this
    // 2.绑定this
    // 边界判断,判断绑定对象是否为空
    // Object()方法可以根据参数的值的类型返回相应的基本包装类型的实例
    thisArg=(thisArg!==undefined&& thisArg!==null)?Object(thisArg):window
    thisArg.fn = fn
    // 3.执行函数
    let result=thisArg.fn(...nums)
    // 4.返回函数的结果
    return result
}
function sum(nums1, nums2) {
    console.log(this)
    return nums1+nums2
}
let obj = { name: 'why' }
// console.log(sum.call(this,1,2))
console.log(sum.hycall(obj,1,2))

2.apply方法的实现

// 实现apply方法

// 1.将方法绑定在Function 的原型对象上
Function.prototype.hyapply=function (thisArg, nums){
    // 1.获取函数
    let fn = this
    
    // 2.处理绑定对象
    thisArg = (thisArg!==undefined&& thisArg!==null) ? Object(thisArg) : window
    // 3.执行函数 处理参数,参数为空时赋值为[]
    nums = nums || []
    thisArg.fn = fn
    console.log(thisArg)
    let result = thisArg.fn(...nums)
    delete thisArg.fn

    // 返回函数结果
    return result
}
let obj = { name: 'why' }
function sum(num1, num2) {
    return num1+num2
}

console.log(sum.hyapply(obj,[1,2]))

3.bind方法的实现

// 实现bind方法
Function.prototype.hybind = function (thisArg, ...argus) {
    // 1.获取函数
    let fn = this
    // 2.获取绑定对象
    thisArg = (thisArg !== undefined && thisArg !== null) ? Object(thisArg) : window
    
    function proxyFn(...proxyArgus) {
        thisArg.fn = fn
        let arg = [...argus, ...proxyArgus]
        let result=thisArg.fn(...arg) 
        delete thisArg.fn
        return result
    }
    // 返回新创建的函数
    return proxyFn
}
function sum(...argus) {
   let val= argus.reduce((pre, value) => {
        return pre + value
   })    
    return val
}
let obj = { name:'why'}
let fn=sum.hybind(obj, 1)
console.log(fn(2,3,4))

总结

这是对js中call、apply和bind方法的简单实现,并没有考虑很多边界条件,如如果绑定对象中已经有fn函数名的处理(可以用Symbol类型:symbol表示唯一的值)等等。欢迎大家一起学习讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值