美文网首页
实现call和apply

实现call和apply

作者: 织雪纱奈 | 来源:发表于2019-04-18 10:47 被阅读0次
    Function.prototype.myCall = function (context) {
             var context = context || window
              console.log(context,this)
              // 给 context 添加一个属性
              // getValue.call(a, 'yck', '24') => a.fn = getValue
              context.fn = this
              // 将 context 后面的参数取出来
              var args = [...arguments].slice(1)
              // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
              var result = context.fn(...args)
              // 删除 fn
              delete context.fn
              return result
    }
    
    Function.prototype.myApply = function (context) {
              var context = context || window
              context.fn = this
    
              var result
              // 需要判断是否存储第二个参数
              // 如果存在,就将第二个参数展开
              if (arguments[1]) {
                result = context.fn(...arguments[1])
              } else {
                result = context.fn()
              }
    
              delete context.fn
              return result
    }
    

    相关文章

      网友评论

          本文标题:实现call和apply

          本文链接:https://www.haomeiwen.com/subject/mldzwqtx.html