this 是什么?
JavaScript this 关键词指的是它所属的对象。
它拥有不同的值,具体取决于它的使用位置:
- 在方法中,this 指的是所有者对象
- 单独的情况下,this 指的是全局对象
- 在函数中,this 指的是全局对象
- 在函数中,严格模式下,this 是 undefined
- 在事件中,this 指的是接收事件的元素
首先方法和函数写法区别:
方法:
fullName : function() {
return this.firstName + " " + this.lastName;
}
函数:
function myFunction() {
return this;
}
1 方法中this:
var person = {
firstName: "Bill",
lastName : "Gates",
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
这里this指的是拥有 fullName这个函数的对象也就是 person
2 单独的 this:
var x = this;
在单独使用时,拥有者是全局对象,因此 this 指的是全局对象。
在浏览器窗口中,全局对象是 [object Window]
3 函数中的this:
function myFunction() {
return this;
}
在 JavaScript 函数中,函数的拥有者默认绑定 this。
因此,在函数中,this 指的是全局对象 [object Window]
但是JavaScript 严格模式不允许默认绑定。
因此,在函数中使用时,在严格模式下,this 是未定义的(undefined)。
4 事件处理程序中的 this:
在 HTML 事件处理程序中,this 指的是接收此事件的 HTML 元素:
<button onclick="this.style.display='none'">
点击来删除我!
</button>