实现jS中的-call、apply、bind

call

Function.prototype.myCall = function(thisArg, ...args) {
    //判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
        //将调用函数地址复制给目标对象的fn属性
    thisArg.fn = this
        //通过目标对象去调用fn函数,并返回(这里参数用了数组结构语法,和参数不同,参数是剩余参数语法,将剩余的参数存入数组,就算没有参数也会是空数组)
    let result = thisArg.fn(...args)
        //删除给目标对象上添加的fn属性
    delete thisArg.fn
        //返回通过目标对象调用fn函数返回的结果
    return result
}

apply

Function.prototype.myApply = function(thisArg, arryArg) {
    //判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
    	//将调用函数地址复制给目标对象的fn属性
    thisArg.fn = this
    	//定义一个变量来保存调用fn函数的返回值
    let result
        //如果什么都没传入则直接正常调用
    if (!arryArg) {
        result = thisArg.fn()
    } else {
        //参数是一个数组,这里采用数组结构,如果不是一个迭代对象的话会报错
        result = thisArg.fn(...arryArg)
    }
   		//删除给目标对象上添加的fn属性
    delete thisArg.fn
    	//返回通过目标对象调用fn函数返回的结果
    return result
}

bind

Function.prototype.myBind = function(thisArg, ...arg1) {
    //判断thisArg(要指向的目标对象)的类型,如果是null或者undefined就返回window,否则用Object包装一下
    thisArg = (thisArg !== null & thisArg !== undefined) ? Object(thisArg) : window
    //定义一个that变量保存要调用函数的内存地址
    let that = this
    //bind函数特殊调用bind函数会返回一个函数
    return function(...arg2) {
        //给目标对象添加一个fn属性并保存调用函数的地址
        thisArg.fn = that
        //通过目标对象调用函数,并将返回值存入变量result
        let result = thisArg.fn(...[...arg1, ...arg2])
        //删除目标对象的fn属性
        delete thisArg.fn
        //返回这个result返回值
        return result
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值