JavaScript this 关键字
本文一起学习下JavaScript中this关键字。this关键字在JavaScript与java有一些差异,不仅仅只对象本身。
1. 引入问题
首先请看下面一段代码,其中 _this = this
我们经常看到,为什么需要这句,看完本文你应该能找到答案。
$("#btn").click(function(){
var _this = this; // (1)
$(".tr").each(function(){
})
})
2. 什么是this
在JavaScript中this关键字引用其所属对象。但依赖在具体什么地方使用所指不同:
- 在方法里, this 引用方法所属对象.
- 独立使用, this 引用全局对象.
- 在函数里, this 引用全局对象.
- 在函数里, 当在 strict 模式时, this 是 undefined.
- 在事件里, this 引用接收事件的元素.
- 对于像 call(), apply() 方法 this 可以引用任何对象.
下面我们分别进行说明。
2.1. 方法里使用this
在对象方法里,this引用方法的拥有者:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
示例的this引用person对象,因为person对象拥有fullName方法。
2.2. this独立使用
独立使用,其拥有者为全局对象,所有this引用全局对象。在浏览器里全局对象是[object Window]
:
var x = this;
但在严格模式下,this值为undefined
。
2.3. 函数里使用this
JavaScript函数中,this默认引用函数拥有者。即引用全局对象[object Window]
:
// "use strict";
function myFunction() {
return this;
}
但在严格模式下不允许默认绑定,因此this值为undefined
。
2.4. 在事件里
在html事件里,this 引用接收事件的html元素:
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
2.5. 显示函数绑定
call(), apply() 方法是JavaScript预定义函数。它们都用于使用另一个对象作为参数调用当前对象的方法。
下面示例中,使用person2作为参数调用 person1.fullName。this引用person2,即使是用person1对象进行调用:
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"John",
lastName: "Doe",
}
person1.fullName.call(person2); // Will return "John Doe"
2.6. 示例分析
$("#btn").click(function(){
var _this = this;//这里this和_this都代表了"#btn"这个对象 (1)
$(".tr").each(function(){
this;//在这里this代表的是每个遍历到的".tr"对象 (2)
_this;//仍代表"#btn"对象
})
})
在第一行 this 引用"#btn",第二行 this 引用 “.tr”。如果要在第二行范围内访问"#btn",则需要事先保存,否则this的值会变化。
3. 总结
本文学习JavaScript中this概念,其在不同场景中引用值不同。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/104126061