js this指向

JavaScript this指向总结

在JavaScript中this永远指向当前函数的主人,即函数的调用对象或事件的调用对象,大致分为以下几种情况。

  1. 单独的this或者全局函数中的this指向window对象
console.log(this);//this => window对象
            
function fn1() {
    console.log(this);//this => window对象              
}
注:在es5严格模式下,this禁止指向window,会报错
  1. 对象的方法中,this指向调用当前方法的对象
var person = {
    username: "钢铁侠",
    show: function(){
           alert("我的名字叫" + person.username);
           alert("我的名字叫" + this.username); //this <==> person
    }
}
 person.show();//this => person对象
 var a = person.show();
 a(); //this => window对象         
上面代码中person.show()由person对象调用,指向person对象,a()是把show方法
重新赋值给a,挂在window对象下面,所以指向window对象。
  1. 构造函数中this指向构造函数构造出来的对象
function Person() {
    //this = new Object();//构造对象时,this指向构造出来的对象
    this.a = 10;
    //return this;
Person.prototype.show = function () {
    console.log(this.age);//this => 构造出来的对象
}
var a1 = new Person();
a1.show(); //this => a1,打印10
  1. 事件绑定中,事件触发的函数中this指向当前绑定的事件
var btn = document.getElementById("btn1");
btn.onclick = function(){
    console.log(this);//this => btn这个点击按钮
};
  1. 定时器中this指向window对象
setInterval(function () {
    console.log(this);//this => window对象
},2000);
  1. 箭头函数中没有this,会默认继承上一次this的指向
var show = () => {
    console.log(this);
}
show();//this => window对象
注:上面箭头函数show()的上一级为window,指向window对象
  1. 强制改变this指向的方法 call(), apply(), bind()
function show(a,b) {
    console.log(this);
    console.log(a,b); 
}
show(1,2);//this => window对象
show.call('call',1,2);//this => 字符串call
show.apply('apply',[1,2]);//this => 字符串apply
show.bind('bind')(1,2);//this => 字符串bind
call,apply,bind方法都会强制将this指向第一个参数,上述方法作用都是相同的。
call方法第二个参数起为传递的参数,返回函数调用的结果。
apply方法只有两个参数,第二个参数为数组,包含传递的参数,返回同call。
bind方法只有一个参数,即指向的值,返回改变指向后的函数,所以在后面再调用一次
函数,把参数传递进去。
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值