apply

文章链接

      Function.prototype.myApply = function (context) {
        if (typeof this !== 'function') {
          throw new TypeError(
            'Function.prototype.myApply - what is trying to be bound is not callable'
          )
        }

        context = context || window
        context._fn = this

        let result
        if (arguments[1]) {
          result = context._fn(...arguments[1])
        } else {
          result = context._fn()
        }

        delete context._fn
        return result
      }
    
      function fn1(age, car) {
        console.log(this.name)
        console.log(age)
        console.log(car)
      }

      const obj = {
        name: '雪月',
      }

      fn1.myApply(obj, [20, '法拉利'])