JS手写call方法

call方法是JS function中内置的一个方法,主要的作用有两个:

  • 改变函数的this指向
  • 向函数中传递参数

使用方式如下:

javascript 复制代码
fn.call(obj, 100, 200)

实现代码示例:

javascript 复制代码
Function.prototype.myCall = function(ctx, ...args) {

  ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
  // 定义一个符号,使其唯一
  const key = Symbol()

  // 这样定义,使符号不可枚举
  Object.defineProperty(ctx, key, {
    value: this,
    enumerable: false
  })
  const r = ctx[key](...args)

  // 运行完没用了,就可以删除掉
  delete ctx[key]

  return r
}

function method(a, b) {
  console.log(this, 'this')
  console.log(a, b, 'args')
}

const a = {
  a: 2
}

method.myCall(a, 2, 3)
// 输出结果:{ a: 2 } this
//          2 3 args


method.myCall(this, 2, 3)
// node 环境没有 this
// 输出结果:{} this
//          2 3 args

method.myCall(1, 2, 3)
// 输出结果:[Number: 1] this
//          2 3 args
相关推荐
Sarvartha7 小时前
final 关键字
java·开发语言
程序员Sunday7 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
Setsuna_F_Seiei8 小时前
前端转型 Agent 开发 06 之 Agent Memory 记忆系统(让 Agent 更智能,更懂你)
前端·agent·ai编程
zhangzeyuaaa8 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
默_笙9 小时前
🌊 向量库和 ES 都查不出"关系",我只好给奶茶建了一张人脉网
前端·javascript
优选资讯9 小时前
标签打印软件怎么对接 Excel 数据
前端·excel
谢亮_vipxieliang9 小时前
用 PHP 构建轻量级 REST API:从路由到鉴权的完整实践
开发语言·后端·php
思无邪6610 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能
一个风轻云淡10 小时前
GCC 和 GDB命令简单解读
java·linux·前端
H.莓飛10 小时前
【数据结构】二叉树_OJ题
linux·开发语言·数据结构·算法