The difference and connection of call apply bind

call apply bind

The common point between the three: the effect is the same, all to change the point of this

The same point of call apply is: changing this point will also execute the function

The difference of call apply is that the parameters are passed in.
Call is to pass in the parameters one by one. Use a comma to separate each parameter.
Apply is to put the parameters in an array and use the array as the parameter
call instance

function fn(name,age) {
    
    
  console.log(this, name,age)
}
fn('张三',13)// 调用结果 window  张三 13

function Person(name,age) {
    
    
    this.name = name
    this.age = age
    fn.call(this,name,age)//将fn的this 绑定为 Person 里面的this
}
let p = new Person('张三',13)// 打印结果 Person {name: "张三", age: 13} "张三" 13

apply instance

function fn(name,age) {
    
    
 console.log(this, name,age)
}
fn('张三',13)//Window 张三 13

function Person(name,age) {
    
    
    this.name = name
    this.age = age
    fn.apply(this,[name,age])//与call 的不同之处就是参数传递
}
let p = new Person('张三',13)//Person {name: "张三", age: 13} "张三" 13

bind just binds this point, and then returns a new function, will not immediately execute the
bind instance

function fn(name,age) {
    
    
   console.log(this, name,age)
}
fn('张三',13)//Window 张三 13
function Person(name,age) {
    
    
    this.name = name
    this.age = age
    this.fn = fn.bind(this,name,age)
}
let p = new Person('张三',13)
p.fn()//Person {name: "张三", age: 13, fn: ƒ} "张三" 13

If bind wants to be called when binding

fn.bind(this,name,age)() //绑定即执行

Guess you like

Origin blog.csdn.net/Chennfengg222/article/details/104692980