相同点:都可以动态改变this的指向
不同点:apply和call的区别在于第二个参数传参的差异,apply第二个参数为一个数组,call的第二个参数为逗号隔开的参数序列。call和bind的区别在于,call使用时会立即调用而bind会返回一个函数,并需要手动调用返回的函数
注意:当第一个参数为string, number, boolean类型时,会根据String, Number, Boolean 构造函数初始化包含原始值的包装对象,当第一个参数为null,undefined时会把this指向window,另外在严格模式下,默认调用会指向window(看最后面的案例)
apply
- 第一个参数:绑定this,
- 第二个参数:以数组形式的实参
function foo(name, age) {
console.log('参数', name, age)
console.log('this', this)
}
foo.apply('apply', ['张三', 24])
// 参数 张三 24
//foo被调用时this的指向 String {'apply'}
call
- 第一个参数:绑定this
- 第二个参数:以逗号隔开的参数序列
function foo(name, age) {
console.log('参数', name, age)
console.log('this', this)
}
foo.call('call', '张三', 24)
// 参数 张三 24
// foo被调用时this的指向 String {'call'}
bind
- 第一个参数:绑定的this
- 第二个参数:以逗号隔开的参数序列
- 返回一个函数,需要手动调用这个函数
function foo(name, age) {
console.log('参数', name, age)
console.log('this', this)
}
const changethis = foo.bind('bind', '张佳', 24)
changethis() // 需要手动调用,参数在此处传也可以
// 参数 张三 24
// foo被调用时this的指向 String {'bind'}
严格模式下的默认调用this的指向
"use strict"
function foo(name,age) {
console.log('参数', name, age)
console.log('foo被调用时this的指向', this)
}
// foo('张三', 24)
// 参数 张三 24
// foo被调用时this的指向 Window {window: Window, self: Window, document: document, name: '', location: Location, …}