手写call、apply、bind

这篇博客详细介绍了如何手写 JavaScript 中的 call、apply 和 bind 方法,通过创建临时属性并利用 this 指针改变函数调用上下文。示例代码展示了这些方法在 Person 对象上的应用,演示了如何将 Person1 的属性与 Person.say 方法结合,从而改变方法的执行环境。
摘要由CSDN通过智能技术生成
// 手写call、apply、bind
// 实现思路
// 通过对象属性的方式调用函数,这个函数里面的this指向这个对象
// 每次调用新增 一个symbol属性,调用完删除
// 这个symbol属性就是调用mycall方法的函数
// 函数形参中使用…ary是将多个形参都放到了一个数组里,在函数内部使用arg这个变量时,就是包含所有形参的数组
// 在调用context fn时候,…arg是为了展开数组,依次传入参数调用函数


let Person = {
    name: 'Tom',
    say (test1,test2) {
        console.log(`我叫${this.name},今年${this.age}岁,test1是${test1},test2是${test2}`)
    }
}

let Person1 = {
    name: ' Tom111',
    age: '18'
}


Function.prototype.myCall = function (context, ...arg) {
    context = context || window
    const fn = Symbol('temporary')
    context[fn] = this;
    context[fn](...arg);
    delete context[fn]
}

Function.prototype.myApply = function (context,arg) {
    context = context || window
    const fn = Symbol('temporary')
    context[fn] = this;
    context[fn](...arg);
    delete context[fn]
}

Function.prototype.myBind = function (context,...arg) {
    const _this = this;
    return function () {
        return _this.myCall(context, ...arg)
    }
}

Person.say.myCall(Person1, 'test1Content', 'test2Content')
Person.say.myApply(Person1,['test1Content', 'test2Content'])
Person.say.myBind(Person1,'test1Content', 'test2Content')()


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值