手写apply与call

171 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第10天,点击查看活动详情

手写apply

    let person = {
      say:function(){
        return this.name
      }
    }
    Function.prototype.mycall = function(context){
      if(typeof this !== 'function'){
        throw new Error('error')
      }
     context = context || window
    
     context.fn = this
      if(arguments[1]){
      reslut =  context.fn(...arguments[1])
      }else{
        reslut = context.fn()
      }
      return reslut
    }
    console.log(person.say.mycall({name:'伍美霖'},[1,2,3]));

手写call

 let person = {
      getName: function () {
        console.log(this);
        return this.name
      }
    }
    let person1 = {
      name: 'Kobe'
    }
    Function.prototype.mycall = function(context){
      //这里this要是一个函数functio
      if(typeof this !== 'function'){
        throw new console.error('error');
      }
      //考虑参数 拿到第一个除外的参数
      let ages = [...arguments].slice(1)

      context = context || window

      // 假设context有个方法fn
      context.fn = this
      return context.fn(...ages)
    }
    console.log(person.getName.mycall({name:'伍美霖'}, 1, 2, 3));