JS中this用法详解
this是JS语言的一个关键字,只能在函数中运行。this可以指向当前代码运行对象本身或者是全局对象。也可以通过apply()方法改变函数的调用对象。下面雷雪松详细的讲解下JS中this的用法。
1、在函数中,this就代表全局对象Global。
1 2 3 4 5 | var x = 9; function test(){ console.log(this.x); } test();//this指向全局对象 |
2、在对象的函数中,this指向对象本身。
1 2 3 4 5 6 7 | var obj={}; obj.x = 10; obj.func = function(){ console.log(this.x); } obj.func ();//对象obj,输出10 console.log(obj); |
3、在构造函数生成对象时,this指向新对象。
1 2 3 4 5 6 7 | var x = 2; function test(){ this.x = 1; } var obj = new test(); console.log(obj.x);//对象obj,输出1 console.log(x);//2 |
4、apply函数的用法,可以传对象名,也可以不传。不传的时候指向全局对象。
1 2 3 4 5 6 7 8 9 10 11 | var x = 0; var otherObj = {x:10}; function test(){ console.log(this.x); } var obj={}; obj.x = 1; obj.func = test; obj.func ();//对象o,输出1 obj.func .apply(); //全局,输出0 obj.func .apply(otherObj); //对象otherObj,输出10 |
最后,雷雪松总结下JS中this用法,如果在函数中运行,就指向全局对象,在对象中,就指向当前对象本身。
来源:JS中this用法详解
2019年5月5日 下午8:29
好文章!666,学习了