call apply bind 的实现

this重定向

详细解析 Function.prototype.mybind 方法

定义与目的
  • 定义: 这段代码是在 Function.prototype 上定义了一个名为 mybind 的方法,目的是为了模拟 JavaScript 原生 Function.prototype.bind 的功能。
  • 目标: 允许你将一个函数绑定到特定的上下文 (context) 并预先设置一些参数,从而返回一个新的函数,这个新函数在被调用时会使用预设的上下文和参数。
工作流程
  1. 接收参数:

    • context: 指定函数调用时的上下文对象。
    • ...args1: 传递给新函数的预设参数列表。
  2. 处理逻辑:

    • 上下文检查: 如果 contextundefinednull,则将其默认设置为全局对象 (windowglobal,取决于环境)。
    • 保存原始函数引用: 使用 _this 变量存储当前函数的引用,以备后续使用。
  3. 返回新函数:

    • 新函数接收任意数量的参数 (...args2)。
    • 在新函数内部:
      • _this 赋值给 context.__fn,创建一个临时属性用于调用原函数。
      • 合并预设参数 args1 和新函数调用时传入的参数 args2
      • 执行 context.__fn,即调用原函数,并传入合并后的参数列表。
      • 删除 context.__fn 属性,避免污染 context 对象。
      • 返回原函数的执行结果。
示例应用

假设有一个函数 sayHello(name),我们想要预先设置 name 参数,并且改变函数调用时的上下文。

Function.prototype.mybind = function(context, ...args1) {
  context = (context === undefined || context === null) ? window : context
  let _this = this
  return function(...args2) {
    context.__fn = _this
    let result = context.__fn(...[...args1, ...args2])
    delete context.__fn
    return result
  }
}
function sayHello(name) {
  console.log(`Hello, ${name}!`);
}
// 使用 mybind 方法
const greetJohn = sayHello.mybind(this, 'John');
greetJohn(); // 输出 "Hello, John!"

Function.prototype.myapply 方法详解

Function.prototype.myapply = function(context, args) {
  context = (context === undefined || context === null) ? window : context
  context.__fn = this
  let result = context.__fn(...args)
  delete context.__fn
  return result
}

Function.prototype.mycall 方法详解

Function.prototype.mycall = function(context, ...args) {
  context = (context === undefined || context === null) ? window : context
  context.__fn = this
  let result = context.__fn(...args)
  delete context.__fn
  return result
}
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值