方法call()、apply()、bind()都保存在函数的prototype名下(因此每个函数都可以直接调用)。都用于改变函数的执行环境。
call()和apply()
call()和apply()实际功能一致。
call()和apply()在原函数拥有参数的时候,不能只有一个参数了。
function add(num1,num2){
console.log(num1+num2);
}
function show(num1,num2){
return add.call(null,num1,2);
}
show(2,3); //输出结果为4
function add(num1,num2){
console.log(num1+num2);
}
function show(num1,num2){
return add.call(null,num1);
}
show(2,3); //输出结果为NAN
在非严格模式下,call(null) 等价于 call(this) 和 call(undefined)
call()必须把函数参数写全,否则无法正确运行。
apply()可以理解为,第二个参数如果需要,必须传入全部参数组成的一个数组,或者arguments。
bind()
call()和apply()是直接调用,而bind()的作用:创建一个函数的实例,执行环境变为bind的参数。对的,只是创建一个函数实例,因此一般需要以值的形式传递之。
var cat = {color:"blue"};
window.color = "red";
function showColor(){
console.log(this.color);
}
showColor.bind(cat); //没有任何输出
showColor.bind(cat)(); //输出blue
var newShowColor = showColor.bind(cat);
newShowColor(); //输出blue
bind()可用于setTimeout()、setInterval()或者事件处理(document),被绑定的函数也会用掉更多的内存。
自定义的bind()
function bind(fn,arg){
return function(){
return fn.apply(arg,arguments);
}
}
这里的arg是执行环境对象,arguments是fn函数本身的参数。
bind(showColor,cat);等价于showColor.bind(cat);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。