当前位置:网站首页>The difference between call and apply and bind

The difference between call and apply and bind

2022-06-11 06:06:00 No baldness

Reference link : difference
The same thing :
call and apply and bind Are used to rebind this The direction of , And you can pass parameters .

const obj = {
    
    name:'obj',
    fun1:function (){
    
        console.log(this.name)
    }
}
const person = {
    
    name:'person',
    age:'22'
}
obj.fun1.apply(person)  // person
obj.fun1.call(person)  // person
obj.fun1() // obj
obj.fun1.bind(person)()  // person

Of a normal function this Point to the caller for it , If not changed this Point to , So use obj.fun1() What you get is obj, Then we use apply、call、bind To change this The direction of . This is what they all have in common .
Difference :

  1. It's not the same .call and bind The method of passing parameters is , separate ,apply The method of passing parameters is parameter array
    1. for example :fun1.call( object , Parameters 1, Parameters 2, Parameters 3...)
    2. fun1.bind( object , Parameters 1, Parameters 2, Parameters 3...)()
    3. fun1.apply( object ,[ Parameters 1, Parameters 2, Parameters 3...])
  2. Different return values .bind Returns a function , Need to call... Again .call and apply Direct return function call .
原网站

版权声明
本文为[No baldness]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110553223858.html