美文网首页
JavaScript 中 call()、apply()、bind

JavaScript 中 call()、apply()、bind

作者: 大嵩的格洛米 | 来源:发表于2021-05-17 22:03 被阅读0次
    var name = 'gromy',age=29
    var animal= {
      name:'bicuihong',
      objage:this.age,
      eat:function(){
         console.log(this.name + '年龄' + this.age+' i can eat')
      }
    }
    console.log(person.objage) //29
    person.eat()  //bicuihong年龄undefined i can eat
    
    var dname='dog'
    function say(){
     console.log(this.dname)
    }
    say()// dog
    

    观察这两个方法的this,第一个实例的this指向person实例,第二个指向window

    call()、apply()、bind() 都是用来重定义 this 这个对象的!

    var name = 'gromy',age=29
    var animal= {
      name:'bicuihong',
      objage:this.age,
      eat:function(){
         console.log(this.name + '年龄' + this.age+' i can eat')
      }
    }
    var monkey={
      name:'sunwukong',
      age:500
    }
    animal.eat.call(monkey)// sunwukong年龄500 i can eat
    animal.eat.apply(monkey)// sunwukong年龄500 i can eat
    animal.eat.bind(monkey)()// sunwukong年龄500 i can eat
    

    对比call 、bind 、 apply 传参情况下

    var name = 'gromy',age=29
    var animal= {
      name:'bicuihong',
      objage:this.age,
      eat:function(a,b){
         console.log(this.name + '年龄' + this.age+' i can eat ilike'+a+','+b)
      }
    }
    
    var monkey={
      name:'sunwukong',
      age:500
    }
    animal.eat.call(monkey,'banana','apple') 
    // sunwukong年龄500 i can eat ilikebanana,apple
    animal.eat.apply(monkey,['banana','apple'])
    // sunwukong年龄500 i can eat ilikebanana,apple
    animal.eat.bind(monkey,'banana','apple')()
    // sunwukong年龄500 i can eat ilikebanana,apple
    animal.eat.bind(monkey,['banana','apple'])()
    //unwukong年龄500 i can eat ilikebanana,apple,undefined
    

    从上面四个结果不难看出:
    call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象,第二个参数差别就来了:
    call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,直接放到后面 obj.myFun.call(db,'成都', ... ,'string' )。
    apply 的所有参数都必须放在一个数组里面传进去 obj.myFun.apply(db,['成都', ..., 'string' ])。
    bind 除了返回是函数以外,它 的参数和 call 一样。
    当然,三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object 等等!

    相关文章

      网友评论

          本文标题:JavaScript 中 call()、apply()、bind

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