call、apply and bind

81 阅读1分钟

call() and apply()

 function a(){
     console.log('hi')
 }
 
 a.call() equals a()
 a() is shorthand the a.call()
 a.apply() do the same thing for now

call() and bind() 改变this对象的指向,第一个参数是this要指向的对象,可添加参数

不带参数的使用

 const wizard ={
     name: 'Merlin',
     health: 50,
     heal() {
         return this.health = 100
     }
 }
 
 const archer ={
     name: 'Robin',
     health: 30
 }
 
 console.log('1', archer.health)  //30
 wizard.heal.call(archer)    // 或者 wizard.heal.apply(archer)
 console.log('2', archer.health)  //100

带参数的使用

 const wizard ={
     name: 'Merlin',
     health: 50,
     heal(num1, num2) {
         return this.health += num1 + num2
     }
 }
 
 const archer ={
     name: 'Robin',
     health: 30
 }
 
 console.log('1', archer.health)  //30
 wizard.heal.call(archer, 30, 30) //separated list of arguments
 /*
  apply()用法
  wizard.heal.apply(archer,[30, 30])  //array of parameters
 */
 console.log('2', archer.health)  //90

bind()

bind() returns a new function with a certain context and parameters

不带参数的使用

 const wizard ={
     name: 'Merlin',
     health: 50,
     heal() {
         return this.health = 100
     }
 }
 
 const archer ={
     name: 'Robin',
     health: 30
 }
 
 console.log('1', archer.health)  //30
 const healArcher = wizard.heal.bind(archer)
 hearArcher()
 console.log('2', archer.health)  //100

带参数的使用

 const wizard ={
     name: 'Merlin',
     health: 50,
     heal(num1, num2) {
         return this.health += num1 + num2
     }
 }
 
 const archer ={
     name: 'Robin',
     health: 30
 }
 
 console.log('1', archer.health)  //30
 const healArcher = wizard.heal.bind(archer, 30, 30)
 hearArcher()
 console.log('2', archer.health)  //90  

bind()给定默认参数

    function multiply(a, b){
        return a*b
    }
    
    let multiplyByTwo = multiply.bind(this, 2)
    console.log(multiplyByTwo(4))  // return 8
    
    let multiplyByTen = multiply.bind(this, 10)
    console.log(multiplyByTen(4))  //return 40