手写 call、apply 及 bind 函数

x33g5p2x  于2022-02-28 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(302)

之前在bind和apply以及call函数使用中详解总结过bindapply以及call函数的使用,下面手写一下三个函数。
一、首先call函数

  1. Function.prototype.MyCall = function (thisArg, ...args) {
  2. let fn = this //this指的是当前函数
  3. thisArg = (thisArg === undefined || thisArg === null) ? window : Object(thisArg)
  4. thisArg.fn = fn
  5. args = args || [] //如果arg不存在,就将其设置为[],方便结构
  6. let res = thisArg.fn(...args)
  7. delete thisArg.fn //执行完之后就删除该对象上的属性
  8. return res
  9. }

二、手写apply函数

  1. Function.prototype.MyApply = function (obj, arg) {
  2. let fn = this //this表示函数
  3. // 如果要是obj为undefined或者null时,设置其为window,
  4. // 如果是基本数据类型,则将其设置为对象类型
  5. let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
  6. thisArg.fn = fn
  7. arg = arg || [] //如果arg不存在,则直接赋值为[]
  8. let res = thisArg.fn(...arg)
  9. delete thisArg.fn
  10. return res
  11. }

三、手写bind函数

  1. Function.prototype.MyBind = function(obj, ...args1) {
  2. let fn = this
  3. let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
  4. return function(...args2) {
  5. thisArg.fn = fn
  6. let args = [...args1, ...args2]
  7. let result = thisArg.fn(...args)
  8. delete thisArg.fn
  9. return result
  10. }
  11. }

相关文章