JavaScript中this总是指向一个对象,this实际上是函数被调用时发生的绑定,它指向什么完全取决于函数在哪里被调用。
apply,call,bind和forEach 对this 都是显示绑定
1.apply
fun.apply(thisArg,argArray)
thisArg:这个对象将代替Function类里this对象
argArray:这个是数组或者伪数组,它将作为参数传给Function(args-->arguments)
function foo(){
console.log.apply(obj,arguments);//bb aa
console.log(this.id);//pp
}
var obj = {
id:'pp'
}
foo.apply(obj,['bb','aa'])
2.call
call类似,第一个参数作用相同,只不过是参数列表不一样
fun.call(thisArg, arg1, arg2, ...)
function foo(){
// console.log(arguments,this.id);
console.log.apply(obj,arguments);
console.log(this.id);
}
var obj = {
id:'pp'
}
foo.call(obj,'ab','aa')
3.bind
bind接受一系列参数,和call很相似,第一个参数是this的指向,从第二个参数开始是接收的参数列表。
var obj = {
name: 'Dot'
}
function printName() {
console.log(this.name)
}
var dot = printName.bind(obj)
console.log(dot) // f
dot() // Dot
bind 方法不会立即执行,而是返回一个改变了上下文 this 后的函数。而原函数 printName 中的 this 并没有被改变,依旧指向全局对象 window。
bind和call很相似,区别在于bind方法返回值是函数,我们必须手动去调用,以及bind接收的参数列表的使用。
4.forEach
array.forEach(function(currentValue, index, arr), thisValue)function(currentValue, index, arr) 必须的参数,forEach遍历数组后默认数组元素为参数currentValue传入函数
thisValue 可选的参数,传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值
function foo(){
console.log(arguments,this.id);
}
var obj = {
id:'pp'
}
let arr1 = [1,2,3];
arr1.forEach(foo,obj);//