JavaScript this 关键字
什么是this?JavaScript this关键字引用它所属的对象。
它具有不同的值,具体取决于它的使用位置:
在方法中,this指的是所有者对象。
单独使用,this指的是全局对象。
在函数中,this指的是全局对象。
在一个函数中,在严格模式下,this是undefined。
在某个事件中,this指的是接收事件的元素。
像方法call(),和apply()this可以指到任何对象。
this在方法中
当单独使用时,所有者是全局对象,因此this引用全局对象。在浏览器窗口中,Global对象是window对象:
fullName : function() {
return this.firstName + " " + this.lastName;
}
单独使用this
在对象方法中,this指的是方法的“ 所有者 ”。在此页面顶部的示例中,this引用person对象。
var x = this;
在严格模式下,单独使用时,this也指全局对象window对象:
"use strict";
var x = this;
this在函数中(默认)
在JavaScript函数中,函数的所有者是默认绑定this。因此,在函数中,this指的是全局对象window。
function myFunction() {
return this;
}
JavaScript 严格模式不允许默认绑定。因此,在函数中使用时,在严格模式下,this是undefined。
"use strict";
function myFunction() {
return this;
}
this在事件处理程序中
在HTML事件处理程序中,this指的是接收事件的HTML元素:
<button onclick="this.style.display='none'">
点击移除我!
</button>
对象方法绑定
在这些示例中,this是person对象(person对象是函数的“所有者”):
var person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
换句话说:this.firstName表示this(person)对象的firstName属性 。
显式函数绑定
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); // 将返回 "John Doe"