自己实现call、apply、bind方法

举报
楚楚冻人玥玥仙女 发表于 2021/11/19 00:28:57 2021/11/19
【摘要】 一、实现call方法 代码: Function.prototype.myCall = function (context) { if(context == null){ context =...

一、实现call方法

  • 代码:
Function.prototype.myCall = function (context) {
  if(context == null){
    context = window;
  }
  context.fn = this;
  const arg = [...arguments].slice(1);
  const ret = context.fn(...arg);
  delete context.fn;
  return ret;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 使用:
function fn1(a, b) {
  console.log('this : ', this);
  console.log(a, b);
  return a + b;
}
const result = fn1.myCall({name: 'jal'}, 150, 100);
console.log(result);
/*
this :  {name: "jal", fn: ƒ}
3 150 100
250
*/

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

二、实现apply方法

  • 代码:
Function.prototype.myApply = function (context, arr) {
  if(context == null) {
    context = window;
  }
  context.fn = this;
  let ret;
  if(arr == null){
    ret = context.fn();
  }else {
    ret = context.fn(...arr);
  }
  delete context.fn;
  return ret;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 使用:
function fn1(a, b) {
  console.log('this : ', this);
  console.log(a, b);
  return a + b;
}
const result = fn1.myApply({name: 'cathy'}, [2, 4]);
console.log(result);
/*
this :  {name: "cathy", fn: ƒ}
3 2 4
6
*/

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

三、实现bind方法:

  • 代码:
Function.prototype.myBind = function (context) {
  if(context == null){
    context = window;
  }
  const arg = [...arguments].slice(1);
  const _this = this;
  
  return function F () {
    if(this instanceof F) {
      return _this.call(this, ...arg);
    }
    return _this.call(context, ...arg);
  }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 使用:
function fn1(a, b) {
  console.log('this : ', this);
  console.log(a, b);
  return a + b;
}
const fn2 = fn1.myBind({name: 'yibo'}, 6, 7);
const result = fn2();
console.log(result);
/*
this :  {name: "yibo"}
3 6 7
13
*/

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

文章来源: blog.csdn.net,作者:爱玲姐姐,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jal517486222/article/details/104842902

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。