bind、call、apply区别

 

 

 

bind、call、apply都是用来改变函数内部this指向的方法,使用上仅有细微差别


一、代码

   function person(p1, p2, p3) {
        console.log('this: ', this)
        console.log('name: ', this.name)
        console.log('传递的参数p1: ', p1)
        console.log('传递的参数p2: ', p2)
        console.log('传递的参数p3: ', p3)
    }

    let obj1 = {
        name: 'zhangsan',
        age: 17
    }
let obj2
= { name: 'sunwu', age: 18 } let obj3 = { name: 'aguang', age: 19 }

二、bind 应用场景(一切不需要立即执行的情况,如,点击事件触发某个函数执行,需要改变函数内this指向的),只是绑定不立即执行

 1     person.bind(obj1, 33) // bind(this要绑定的对象, 其它参数)
 2 
 3     // bind 如果是绑定后立即执行则,bind立即执行需()
 4     person.bind(obj1, 44)()
 5     /*
 6         运行结果:
 7         this: {name: "zhangsan", age: 17}
 8         name: zhangsan
 9         传递的参数p1: 44
10         传递的参数p2: undefined
11         传递的参数p3: undefined
12      */
13 
14    // bind 使用场景举例:一个按钮单击事件,点击后触发
15     const btn = document.getElementById('btn1');
16     btn.addEventListener('click', person.bind(obj1, 55, 66, 77))
17     /*
18         运行结果:
19         this: {name: "zhangsan", age: 17}
20         name: zhangsan
21         传递的参数p1: 55
22         传递的参数p2: 66
23         传递的参数p3: 77
24      */

三、call

 1    // call 改变函数内部this指针到obj2对象,且传递参数88,99,多个参数可以并列用逗号排开 88,99 ... ,是立即执行
 2     person.call(obj2, 88, 99)
 3     /*
 4         运行结果:
 5         this: {name: "sunwu", age: 18}
 6         name: sunwu
 7         传递的参数p1: 88
 8         传递的参数p2: 99
 9         传递的参数p3: undefined
10      */

四、apply

 1   // bind 改变函数内部this指针到obj3对象,且传递参数[100,200,300],与call区别仅在于apply传递参数是一个数组,多个参数可存在一个数组传递,是立即执行
 2     person.apply(obj3, [100, 200, 300])
 3     /*
 4         运行结果:
 5         this: {name: "aguang", age: 19}
 6         name: aguang
 7         传递的参数p1: 100
 8         传递的参数p2: 200
 9         传递的参数p3: 300
10      */
原文地址:https://www.cnblogs.com/rapale/p/14983255.html