The use and difference of call, apply, and bind

1. call, apply, and bind are all methods of function.prototype , so each function has call, apply, and bind attributes.

call

function.call(thisArg, arg1, arg2, ...)

[thisArg] Mandatory, the this value used when the function function is running, when it is specified as null or undefined, it will be automatically replaced with a global object
[arg1, arg2, ...] parameter list


let objCall ={
    name: "我是 Call"
}


function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}

fn.call(objCall, 1,2,3)

// 参数 =>  1 2 3
// name =>  我是Call

apply 

func.apply(thisArg, [argsArray])

  • [ thisArg] must choose the  call same
  • [ argsArray] optional

let objApply ={
    name: "我是 Apply"
}
function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}
fn.apply(objApply, [1,2,3])
// 参数 =>  1 2 3
// name =>  我是 Apply

bind 

function.bind(thisArg, arg1, arg2, ...)

[thisArg] Required
list of [arg1, arg2, ...] arguments

let objBind ={
    name: "我是 Bind"
}
let objApply ={
    name: "我是 Apply"
}

function fn() {
    console.log('参数 => ', ...arguments)
    console.log('name => ', this.name)
}
let bfn = fn.bind(objBind, 1,2,3);
bfn();

bfn.call(objCall)
bfn.apply(objApply)

// 三个结果一样
// 参数 =>  1 2 3
// name =>  我是 Bind

2. The functions of call, apply, and bind can all change the this point inside the function

Summarize:

1) call, apply and bind can change the this point of the function

2) The first parameter of call, apply and bind is the object to be pointed to by this

3) call, apply, and bind can all pass parameters to the function later. apply is to combine parameters into an array , and call and bind are to list parameters in sequence.

4) call and apply are direct calls, and the this point generated by bind needs to be called manually to change the function .

Guess you like

Origin blog.csdn.net/weixin_50543490/article/details/127992959