1、call方法
格式:函数名.call()
参数:
- 第一个参数:传入该函数this指向的对象,传入什么强制指向什么
- 第二个参数开始:将原函数的参数往后顺延一位
<script>
function show(x, y) {
console.log(this+' '+x + ',' + y)
}
//show(10, 20)//输出Window 10,20
show.call('call', 10, 20)//输出call 10,20
</script>
上面将this指向从window改成call
2、apply方法
格式:函数名.apply()
参数:
- 第一个参数:传入该函数this指向的对象,传入什么强制指向什么
- 第二个参数数组:数组 放入我们原有所有参数
<script>
function show(x, y) {
console.log(this+' '+x + ',' + y)
}
//show(10, 20)//输出Window 10,20
show.apply('apply', [10, 20])//输出call 10,20
</script>
apply使用小技巧:在max、min函数写入数组变量求最大值、最小值
<script>
var arr = [40, 30, 60, 10, 100]
console.log(Math.max.apply(null, arr))//100
console.log(Math.min.apply(null, arr))//10
</script>
3、bind方法
格式:函数名.bind()
参数:
- 传入该函数this指向的对象,传入什么强制指向什么
返回值:改变this之后的一个新函数
<script>
function show(x, y) {
console.log(this+' '+x + ',' + y)
}
var res=show.bind('bind')
res(10,20)//输出bind 10,20
</script>
上面bind函数返回了一个改变了this指向的新数组