浅谈JavaScript中this的指向

浅谈JavaScript中this的指向

1.默认指向,this默认指向的是window对象
console.log(this);//打印的是window
2.函数调用时
2.1独立调用,this指向window对象
function test(){
    console.log(this);//打印的是window
}
window.test();//简写test()
2.2函数作为某个对象的方法时,this指向的是当前对象
let obj = {
     name:"test",
     show:function(){
     console.log(this);//这个打印出来的是window
	}
}
let a = obj.show;//a就是function(){console.log(this);}
a();//window.a();
3.指向当前对象
let obj = {
   name:'test',
   age:19,
   show:function(){
    console.log(this);
    }
}
obj.show();//打印出来的是Object
4.this指向绑定的元素,当函数作为一个事件处理函数的时候,这时this是指向绑定的元素
<body>
	<button>点击</button>
</body>
<script>
	document.querySelector("button").onclick=function(){
	console.log(this);
	}
</script>
5.改变this的指向
5.1 call()
let obj={
    name:'hello',
    age:19,
    show:function(x,y){
        console.log(this);//Object
        console.log(this.name);//张三
        console.log(this.age+x+y);//50
    }
}
let obj2={
    name:'张三',
    age:30
}
obj.show.call(obj2,10,10);
5.2 apply()
let obj={
    name:'hello',
    age:19,
    show:function(x,y){
        console.log(this);//Object
        console.log(this.name);//张三
        console.log(this.age+x+y);//60
    }
}
let obj2={
    name:'张三',
    age:30
}
obj.show.apply(obj2,[10,20]);
es5中bind()
let obj={
    name:'hello',
    age:19,
    show:function(x,y){
        console.log(this);//Object
        console.log(this.name);//张三
        console.log(this.age+x+y);//60
    }
}
let obj2={
    name:'张三',
    age:30
}
let test = obj.show.bind(obj2);
test(10,20);
6.箭头函数的this的指向,它的this指向始终是指向的外层作用域
由于箭头函数不绑定this, 它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值
let obj = {
    name:"test",
    show:()=>{
        console.log(this);//打印出Window
    }
}
obj.show();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ForzaFerrari

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值