call、apply、bind三者的用法和区别

2021-09-26  本文已影响0人  April_LY09
let fn = function(x, y){
    console.log(x, y)
    console.log(666, this)
}
let obj1 = {name:'张三'}, obj2 = {name:'李四'}, obj3 = {name:'王五'}

let a = fn.call(obj1, 1, 2) // 自动执行,console.log(a, b) 输出 1 2 ,console.log(666, this) 输出  666 obj1 ,注意 call 后面的参数
console.log(a)  //  call 不返回值  输出 undefined

let b = fn.apply(obj2, [1, 2])  // 自动执行,console.log(a, b) 输出 1 2 ,console.log(666, this) 输出 666 obj2 ,注意 apple 后面的参数变化
console.log(b)  // apply 不返回值  输出 undefined

let c = fn.bind(obj3, 1, 2) // 不会自动执行
console.log(c)
/* bind返回方法,输出这个方法
    ƒ (a, b){
        console.log(a, b)
        console.log(666, this)
    }
*/
c() // 执行方法得到,console.log(a, b) 输出 1 2 ,console.log(666, this) 输出 666 obj2

/* 
* 总结:1、call 和 apply  都让 this 改变为 obj 了,但是绑定的时候立即执行。(返回值是undefined)
*   2、注意 call 和 apple 的传参方式不同
*   3、bind 会返回一个函数 把 fn 中的 this 预处理为 obj,此时 fn 没有执行,当点击的时候才会把 fn 执行。(会永久改变this指针)
*/
上一篇 下一篇

猜你喜欢

热点阅读