1、先看示例
const a = function (pars){
console.log(pars)
}
function f(){
return a.apply(a,arguments)
}
function g(){
return a.bind(a,...arguments)()
}
function e(){
return a.call(a,...arguments)
}
f('apply')
g('bi','nd')
e('call')
/**
output:
apply
bi
call
*/
apply方法只有两个参数
如果需要使用arguments接收多个参数,需要使用数组,如果没有使用[arguments],但是却传递了多个参数,则最终指挥输出第一个参数,如下
const a = function (pars){
console.log(pars[0] + pars[1])
}
function f(){
return a.apply(a,[arguments])
}
function h(){
return a.apply(a,arguments)
}
f('apply','apply')
//output: f():applyapply h():apply
bind方法是可以接收多个arguments
//如果bind使用了...arguments,调用时传递了多个参数,但是方法里却只有一个形参
//最终也只会输出第一个参数,即形参要与实参一一对应
const a = function (pars){
//需要输出具体的下标
console.log(pars[0])
}
function g(){
//没有使用...arguments
return a.bind(a,arguments)()
}
//如果传递多个参数,则下标是哪个,就输出哪个
g('bi')
//output:bi
//使用...arguments,则可以接受任意多的参数
function j(){
return a.bind(a,...arguments)()//与call和apply不同,后面多了对括号
}
call与bind相同,bind后面比call多一对括号