• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

mandyGuan12

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

手写call方法

<script>
    // <!-- 实现mycall方法, 功能和调用形式与call一致 -->

    // 原型定义一个mycall方法, 大家都能调用
    Function.prototype.mycall = function (thisArg, ...argN) {
        // console.log('mycall方法被调用了');
        // 设置this并调用原函数
        // 接收剩余参数
        // 将动态添加的属性删掉
        // 返回结果
        thisArg.f = this
        const res = thisArg.f(...argN)
        delete thisArg.f
        return res
    }

    const person = {
        name: 'mandy',
        age: 21
    }

    function fun(numA, numB) {
        console.log(this);
        console.log(numA, numB);
        return numA + numB;
    }

    const result = fun.mycall(person, 10, 11)
    console.log('result:' + result);
    const result2 = fun.call(person, 20, 21)
    console.log('call - result:' + result2);
</script>

.

.

.

调试结果:

.

.

..

在thisArg.f = this中动态添加了一个f方法并将fun设置给了这个方法
如果有同名属性f怎么办?
使用symbol进行调优

Symbol 代表创建后独一无二且不可变的数据类型,它主要是为了解决可能出现的全局变量冲突的问题

const internalF = Symbol('internalF')
        // 使用[]将internalF解析为属性名
        thisArg[internalF] = this
        const res = thisArg[internalF](...argN)
        delete thisArg[internalF]
        return res

.

.

.

posted on 2024-09-05 16:41  番茄仔Mandy  阅读(16)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3