call函数的实现


前言

call()方法是使用一个指定this值和单独给出的一个或多个参数来调用函数,本文就是手写call方法


一、call函数的实现步骤

  1. 判断调用对象是否为函数
  2. 判断传入上下文对象是否存在,如果不存在,则设置为window
  3. 处理传入的参数,截取第一个参数后的所有参数
  4. 将函数作为上下文对象的一个属性
  5. 使用上下文对象来调用这个方法,并保存返回结果
  6. 删除刚才新增的属性
  7. 返回结果

二、call函数实现

1.call函数

代码如下(示例):

  Function.prototype.myCall = function (context) {
    if (typeof this !== 'function') {
      console.error('type error')
      return
    }
    let args = [...arguments].slice(1),
      result = null
    context = context || window
    context.fn = this
    result = context.fn(...args)
    delete context.fn
    return result
  }

2.test

代码如下(示例):

 //(1)
  const obj = {
    count: 10,
  };

  function fn (x, y, z) {
    return this.count + x + y + z;
  }

  let b = fn.myCall(obj, 1, 2, 3); // 执行函数 fn,返回 16
  
  console.log(b)
  //(2)
  function Product (name, price) {
    this.name = name;
    this.price = price;
  }

  function Food (name, price) {
    Product.myCall(this, name, price);
    this.category = 'food';
  }

  function Toy (name, price) {
    Product.myCall(this, name, price);
    this.category = 'toy';
  }

  var cheese = new Food('feta', 5);
  var fun = new Toy('robot', 40);
  
  console.log(cheese)
  console.log(fun)

在这里插入图片描述


总结

以上就是call函数的实现,该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值