call、apply、bind方法的使用及区别

199 阅读2分钟

this指向的形式4种

a.如果是一般函数,this指向全局对象window;

b.在严格模式下"use strict",为undefined.

c.对象的方法里调用,this指向调用该方法的对象.

d.构造函数里的this,指向创建出来的实例.

改变this指向的方式3种

call

  • call方法在调用的时候会执行函数
  • 返回值是原函数中定义的返回值
function.call(thisObject,value,value……)

1. 第一个参数是this的指向;
2. 第二个参数以及后面的参数都是需要传的参数,以逗号的格式分隔;

apply

  • apply方法在调用的时候会执行函数
  • 返回值是原函数中定义的返回值
function.call(thisObject,[value,value……])

1. 第一个参数是this的指向;
2. 第二个参数是数组,是需要向函数传递的参数;

bind

  • bind方法在调用的时候不会执行函数
  • 返回值是一个新的函数
function.call(thisObject,value,value……)

1. 第一个参数是this的指向 ;
2. 第二个参数以及后面的参数都是需要传的参数,就算调用的时候有传递新的参数,也会以之前预传的参数为准;    

代码实践

call

function demoCall(a,b) {
    console.log(a,b)//1,2
    console.log(this,this.name)//{name: 666}   666
    return a+b
}
let resultCall = demoCall.call({name:666},1,2)
console.log(resultCall)//3

apply

function demoApply(a,b) {
    console.log(a,b)//2,3
    console.log(this,this.name)//{name: 999} 999
    return a+b
}
let resultApply = demoApply.apply({name:999},[2,3])
console.log(resultApply)//5

bind

 function demoBind(a,b) {
    console.log(a,b)//undefined,undefined  6,7            6,7
    console.log(this)//window              {name: 222}    {name: 222} 
    return a+b
}
demoBind()

let resultBind = demoBind.bind({name:222},6,7)
resultBind()

console.log(resultBind)//原函数

let Bind = resultBind(2,3)
console.log(Bind)//13resultBind(2,3) 调用时传递的参数没有效果,因为bind是以之前预传的参数为准;

参数的区别:

function fn(a, b, c) {
    console.log(a, b, c);
}
var fn1 = fn.bind(null, 'Dot');
fn('A', 'B', 'C');	//A B C
fn1('A', 'B', 'C');           // Dot A B
fn1('B', 'C');                // Dot B C
fn.call(null, 'Dot');      // Dot undefined undefined

区别:

bind与call和apply的区别:
返回值的区别:
bind的返回值是一个函数,而call和apply是立即调用。
参数使用的区别:
bind与call一样是从第二个参数开始将想要传递的参数一 一写入。
但call是把第二个及以后的参数作为fn方法的实参传进去,而fn1方法的实参实则是在bind中参数的基础上再往后排。

文章参考处:

https://blog.csdn.net/weixin_46500485/article/details/108344742
https://blog.csdn.net/weixin_43606158/article/details/90137845
https://www.pianshen.com/article/9946679251/