JavaScript this关键字
面向对象语言中的this表示当前对象得到一个引用
但在JavaScript中的this不是固定的不变的,会随着执行环境的改变而改变
在方法中,this 表示该方法所属的对象。
在对象方法中, this 指向调用它所在方法的对象。
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
在这个个实例中,this 表示 person 对象。
fullName 方法所属的对象就是 person
如果单独使用,this 表示全局对象。
单独使用 this,则它指向全局(Global)对象。
在浏览器中,window 就是该全局对象为 [object Window]:
var x = this;
严格模式下,如果单独使用,this 也是指向全局(Global)对象。
"use strict";
var x = this;
在函数中,this 表示全局对象。
在函数中,函数的所属者默认绑定到 this 上。
在浏览器中,window 就是该全局对象为 [object Window]:
function myFunction() {
return this;
}
在函数中,在严格模式下,this 是未定义的(undefined)。
严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
"use strict";
function myFunction() {
return this;
}
在事件中,this 表示接收事件的元素
在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:
<button onclick="this.style.display='none'">
点我后我就消失了
</button>
类似 call() 和 apply() 方法可以将 this 引用到任何对象。
apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象