call 和apply的功能是一致的,两者的细微差距call以参数表来接受被调用函数的参数,而apply是以数组来接受被调用函数的参数。
call和apply的语法分别是:
func.call(thisArg[,arg1[,args2[,...]]])
func.apply(thisArg[,argsArray])
我们以下面一段代码为例介绍call的工作机制
var someuser = {
name: 'byvoid',
display:function(){
console.log(this.name+'says'+words);
}
};
var foo = {
name: 'foobar'
};
someuser.display.call(foo,'hello') //输出 foobar says hello
someuser.display是被调用的函数,它是通过call将上下文改变为foo对象,因此在函数体访问this.name时,实际上访问的是foo.name,因而输出foobar
但是重复使用call和apply会使代码变得不直观,针对这种情况。我们可以使用bind方式来永久地绑定函数的上下文,使其无论谁被调用,上下文都是固定的
func.bind(thisArg[,arg1[,arg2[,...]]])
var someuser = {
name : 'byvoid',
func:function(){
console.log(this.name);
}
}
var foo = {
name:'foobar'
}
func = someuser.func.bind(foo);
func() //输出 foobar
func2 = func;
func2();//输出foobar
func2直接将绑定的func赋值过来,与func行为完全相同
bind还有一个重要的功能,绑定函数表
bind绑定函数表
https://blog.csdn.net/zwy15841139493/article/details/89188906