在javascript中,call和 apply 都是为了改变函数体内部 this的指向。
<script>
/*
this指向
事件中的this,指向事件源。
普通函数中的this指向window
*/
var stu={
name:'zs'
}
function add(x,y){
console.log(x,y)
console.log(this)
}
</script>
1.call()
函数名.call(对象,实参) 直接调用函数 修改this的指向,指向的就是传递的对象。
add(1,2);
add.call(stu,1,2)
输出结果:
2.apply()
函数名.apply(对象,[实参])直接调用函数 修改this的指向,指向的就是传递的对象。
add.apply(stu,[1,2])
输出结果:
3.bind()
函数名.bind(对象,实参) 返回一个新的函数,不会直接调用,修改this的指向,指向的就是传递的对象。
fn=add.bind(stu,1,2);
fn();
输出结果: