js handwritten call and apply (basically the articles on the Internet are not perfect and have bugs)

call

***注意很多人手写这个方法时直接往context上挂,但是如果context时基本数据类型就错了

Function.prototype.myCall = function (context) {
    
    
  // 先判断调用myCall是不是一个函数
  // 这里的this就是调用myCall的
  if (typeof this !== 'function') {
    
    
    throw new TypeError("Not a Function")
  }

  // 不传参数默认为window
  context = context || window

  // 保存this 
  context.__proto__.fn = this

  // 保存参数
  let args = Array.from(arguments).slice(1)   //Array.from 把伪数组对象转为数组

  // 调用函数
  let result = context.fn(...args)

  delete context.__proto__.fn
  return result

}

console.log(Object.prototype.toString.myCall(123));

applay

Function.prototype.myApply = function (context) {
    
    
      // 判断this是不是函数
      if (typeof this !== "function") {
    
    
        throw new TypeError("Not a Function")
      }

      let result

      // 默认是window
      context = context || window

      // 保存this
      context.__proto__.fn = this

      // 是否传参
      if (arguments[1]) {
    
    
        result = context.fn(...arguments[1])
      } else {
    
    
        result = context.fn()
      }
      delete context.__proto__.fn

      return result
    }

Guess you like

Origin blog.csdn.net/weixin_44441196/article/details/125259898