美文网首页
bind、call、apply

bind、call、apply

作者: 飞奔的小白 | 来源:发表于2022-10-09 17:10 被阅读0次
    this 指向谁
    var name = "freemen"
    function sayAuthor(){
      var name = 'mkw'
      console.log(`this.name`,this.name)
    }
    sayAuthor()              //freemen
    window.sayAuthor() //freemen
    
    
    
    
    //小王去面试
    //小王去招聘会现场参加面试 招聘的企业是腾讯和阿里
    //腾讯和阿里的面试官分别是 freemen 和 vinko ,阿里的vinko 临时有事请腾讯的fenmen来帮忙
    //freemen 来到阿里的面试现场 谁  你好 我是vinko 我的公司是阿里
    
    
    
    const Tencent = {
      name:"freemen",
      company:"Tencent",
      time:"2021-11-31",
      address:"BeiJing",
      say(company){
         console.log(`my name is`,this.name)
         console.log(`my company is`,company)
      }
    }
    
    const Alibaba = {
      name:"Vinko",
      time:"2021-11-31",
      address:"BeiJing",
      say(company){
         console.log(`my name is`,this.name)
         console.log(`my company is`,company)
      }
    }
    
    
    Tencent.say('Tencent')
    \\ my name is Tencent 
    \\my company is Tencent
    
    //freemen 替 vinko 面试
    Tencent.say.call(Alibaba,'Alibaba')
    //my name is Vinko
    //my company is Alibaba
    Tencent.say.apply(Alibaba,['Alibaba'])
    
    const say = Tencent.say.bind(Alibaba,'Alibaba')
    say()
    
    
    //总结
    //call 和 apply 传参方式不同
    //bind返回值是函数 和 call 传参一样 
    
    使用场景
    //判断数据类型
    const array = [1,2,3,4]
    const type = Object.prototype.toString.call(array)
    
    类 数组:
    const arrayLike = {
     0:“name”,
     1:   “age”,
      2:“gender”,
      length:3
    }
    const res = Array.prototype.slice.call(arrayLike)
    ['name','age','gender']
    
    

    相关文章

      网友评论

          本文标题:bind、call、apply

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