js实现call

1,实现过程:

//在原型上自定义一个myCall
Function.prototype.myCall = function (thisArg, ...res) {
  //保存一下刚开始调用myCall的主体中的this(指向的是一个函数)
  let fn = this;

  //为了防止传入的参数是数字或字符串无法添加属性,给从传入的参数转换为对象
  thisArg = thisArg ? Object(thisArg) : window;
  //当传递了参数时,给参数添加一个属性,让属性等于刚开始存的函数,相当于修改了fn中的this指向thisArg
  thisArg.fn = fn;
  //相当于又来了一次隐式绑定。在thisArg身上调用fn,此时this就会指向thisArg
  const result = thisArg.fn(...res);
  //因为我们为了改变this给thisArg添加了一个属性fn,用完之后清除一下
  delete thisArg.fn;

  //将调用函数后得到的返回值返回出去
  return result;
};

function foo(name, sex) {
  this.name = name;
  this.sex = sex;
  console.log("foo被调用了");
  console.log(this);
}

const person = {
  age: "18"
};

//foo.myCall属于隐式绑定,当被调用时myCall中的this就是foo中的this
foo.myCall(person, "ls", "女"); //

案例二:

//说到底call内部实现是通过,给call函数中传入的对象添加一个属性等于调用call的那个函数。
//这样调用call函数中的this的指向就会指向传入的对象
const a = {
  name: "zs",
  hobby() {
    console.log(this); //ls
  }
};
const b = {
  name: "ls",
  play: a.hobby //ls
};
b.play();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值