手写JavaScript中的call、apply、bind方法

call方法:

描述:使用一个指定的 this 值(默认为 window) 和 一个或多个参数来调用一个函数。

语法:function.call(thisArg, arg1, arg2, …)

Function.prototype.newCall = function(obj,...args){
    // 首先判断this是否是一个函数
    if(Object.prototype.toString.call(this) !== '[object Function]')
        throw new Error('error in params')
    // 然后判断传入的对象是否存在
    if(obj === null || obj === undefined)
        obj = globalThis
    // 在obj上放一个临时的变量,用于改变this指向
    obj.temp = this
    const result = obj.temp(...args)
    delete obj.temp
    return result
 }
// 测试一下
function person(a,b){
    console.log(this.name)
    console.log(a+b+this.c)
}
var man = {
    name: '男人',
    c: 20
}
person.newCall(man,1,1)

apply方法

描述:与 call 类似,唯一的区别就是 call 是传入不固定个数的参数,而 apply 是传入一个参数数组或类数组。

Function.prototype.newApply = function(obj,arr){
    // 首先判断this是否是一个函数
    if(Object.prototype.toString.call(this) !== '[object Function]')
        throw new Error('error in params')
    // 然后判断传入的对象是否存在
    if(obj === null || obj === undefined)
        obj = globalThis
    // 在obj上放一个临时的变量,用于改变this指向
    obj.temp = this
    let result
    // 判断传入的数组是否为空
    if(!arr){
        result = obj.temp()
    }
    else{
        result = obj.temp(...arr)
    }
    delete obj.temp
    return result
 }
// 测试一下
function person(a,b){
    console.log(this.name)
    console.log(a+b+this.c)
}
var man = {
    name: '男人',
    c: 20
}
person.newApplyl(man,[1,2])

bind方法

描述:bind 方法会创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

Function.prototype.newBind = function(obj,...args1){
   if(Object.prototype.toString.call(this) !== '[object Function]')
       throw new Error('error in params')
   if(obj === null || obj === undefined)
       obj = globalThis
   // 保存原函数
   let that = this
   return function(...args2){
       return that.call(obj,...args1,...args2)
       
   }
}
// 测试一下
function animal(a,b){
    console.log(this.name)
    console.log('我喜欢吃'+a+'和'+b)
}
var dog = {
    name: 'dog'
}
var f = animal.newBind(dog,'肉','骨头')
f()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值