call apply bind 的区别与联系

call apply bind

三者之间的共同点: 作用都是一样的,都是为了改变 this 的指向

call apply 相同点是: 改变this指向的同时也会执行函数

call apply的差异是参数的传递
call 是将参数一个一个传递进去.使用逗号来分隔每个参数
apply 是将参数放到一个数组当中,将数组作为参数
call 实例

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 实例

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 只是绑定 this 指向,然后返回一个新函数,不会立即执行
bind实例

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

如果bind想要在绑定时就调用的话

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

猜你喜欢

转载自blog.csdn.net/Chennfengg222/article/details/104692980