call apply bind
- 共同点:
1、均能改变 this 指向,且指向第一个参数
2、均从第二个参数开始传参
- 不同点
1、call apply 均能立即执行函数,而 bind 是稍后执行,需要执行即在后面添加 ( )
2、call bind 后面参数个数、格式不限制,apply 只有两个参数,第二个参数是数组,为所有参数的集合
<script>
let obj = {
name: 'qwe',
age: 18
}
function fn(obj, num, ss) {
console.log('this指向------', this)
console.log('obj-----', obj)
console.log('num-----', num)
console.log('ss-----', ss)
}
// fn() // this指向------ window
// window.fn() //this指向------ window
// fn.call(obj, 222) // this指向------ {name: "qwe", age: 18}
// // obj----- 222
// // num----- undefined
// // call在执行函数时,函数的参数从第二位开始依次写入
// fn.apply(obj, [1, 25, 66]) // this指向------ {name: "qwe", age: 18}
// obj----- 1
// num----- 25
// ss----- 66
// 只有两个参数, 第二个参数是个数组,为所有参数的集合
// call 和 apply 用法几乎一样,改变的 this 指向,均指向第一个参数,且函数立即执行
// 非严格模式下,如果第一个参数为null 或者 undefined, 则指向 window ,严格模式下,第一个参数是什么,this就指向什么
// bind 是稍后执行,如要立即执行函数,需要在后面添加 ()
fn.bind(obj, 222, 333)() // this指向------ {name: "qwe", age: 18}
// obj----- 222
// num----- 333
// ss----- undefined
fn.bind(obj, [222, 333])() // this指向------ {name: "qwe", age: 18}
// obj----- [222,333]
// num----- undefined
// ss----- undefined
</script>