改变this绑定指向的方法

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);//

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值