当前位置: 首页 > news >正文

apply,call,bind手写

手写apply、call、bind
确定this 的值
  1. 全局执行环境

     <script>'use strict'console.log('222',this);
    </script>
    

    严格模式下和非严格模式下都是全局对象 (window)

  2. 函数内部

    'use strict'
    function  inFn() {console.log('inFn',this); 
    }
    

    严格模式下是undefined;非严格模式下是全局对象 (window)

  3. 对象方法

    'use strict'
    const peason = {name: '小毅',getName:()=>{console.log('getName', this); // windowreturn this.name},setName(name) {console.log('setName', this); // 对用对象peasonthis.name = name}
    }
    

    严格模式下和非严格模式下结果一样;getName 方法是箭头函数,this是window; setName 方法是普通函数,this 是调用者 peason

手写call 方法
  1. 在Function 对象上实列上增加myCall 方法

    // 定义 myCall方法
    Function.prototype.myCall = function () {}
    // Object.prototype.myCall = function () {}// 
    function add(a, b) {}// 调用
    add.myCll({},a,b)
    

    1、Function或者Object 对象上定义myCall方法,调用的时候,可以根据原型链拿到myCall 方法

    2、add 方法也可以说是对象, 因为add instanceof Object ==> true

    3、根据上文《确定this 的值》 第三点,在对象方法里面的this是调用者,所以add.myCall({},a,b) , add 调用myCall ,此时myCall 方法里面的this 为 调用者:add 方法(对象)

    // 手写call
    Object.prototype.myCall = function (target, ...rest) {// this为调用者add,把add 方法放在target对象里target.fn = this//再调用target下的fn,此时调用者是target,所以this为targetconst result = target.fn(...rest) delete target.fn return result
    }const peason = {name: '小毅'}
    // 调用
    add.myCall(peason,1,2)
    
  2. 优化,上面一个版本的call ,可能会把target 对象的fn 属性覆盖掉,使用

    Object.prototype.myCall = function (target, ...rest) {const key = new Symbol()target = target || {}target[key] = thisconst result = target.fn(...rest)delete target[key]return result
    }
    
手写apply 方法

与call 类似,只是apply 接收的参数是数组

Function.prototype.myApply = function (target,rest) {const key = new Symbol()target = target || {}target[key] = thisconst result = target.fn(rest)delete target[key]return result
}
手写bind

bind 函数绑定是,没有执行,所以返回的是一个函数;

myBind 方法内的this 是调用者add 方法

myBind 内return 的是箭头函数,所以this 也是add方法

this.mycall 相当于 add.mycall ,同上文 mycall原理相当

// mybind 方法
Function.prototype.myBind=function (target,...rest){return (...rest2)=>{this.myCall(target,...rest,rest2)}
}// 累加  
add(num1,num2,num3,num4){}// add 调用bind
add.myBind(peason,1,2)

http://www.mrgr.cn/news/59490.html

相关文章:

  • 在Selenium中有哪些元素对象操作方法?( ̄﹃ ̄)
  • STMicroelectronics意法半导体车规芯片系列--亿配芯城(ICgoodFind)
  • CSS-层叠性质
  • Telegram机器人的手机部署
  • git命令笔记(速查速查)
  • Nginx+Tomcat 动静分离
  • 质量漫谈一
  • xss-labs靶场第十七关测试报告
  • 照片怎么转换成pdf?盘点6种图片转pdf格式有效方法,直击要点!
  • 【Spring MVC】响应结果和设置
  • linux学习笔记 常用命令记录
  • cookie 简介
  • GEE app:全球油棕,橡胶,其他树木,灌木,裸地,水的可视化界面
  • 基于STM32F103的FreeRTOS系列拓展·内存管理
  • 微信好友智能管理神器:微动RPA,重塑私域流量构建新纪元 批量自动添加好友
  • 说一说QWidget
  • 如何从iconfont中获取字体图标并应用到微信小程序中去?
  • 深入理解 Java 中的抽象类
  • 数组和指针复习
  • 为什么说 zsh 是 shell 中的极品?
  • 地球村上一些可能有助于赚钱的20个思维方式
  • 虚拟机上创建的网站在真机上无法访问的解决办法,以及hosts文件编辑的解决办法
  • 5.15 加载内核映像文件(1)
  • 单目深度估计评价指标及其含义说明
  • 线程同步(互斥锁条件变量)
  • 中药大数据(三)中医知识图谱的创建