1,在方法中使用,此时this代表的是方法拥有者
var car={
color:"red",
name:"bwm",
id:720,
fullname:function(){
return this.name+" "+this.id;
}
};
在上例中,此时的this所代表的则是car这个方法拥有者
2,在函数中使用时,因为在 JavaScript 函数中,函数的拥有者默认绑定 this
function myFunction() {
return this;
}
此时返回的则是[object window]返回全局对象,注意在JS严格模式下,返回的是undefined
"use strict";
function myFunction() {
return this;
}
3,在HTML事件处理程序中,this代表的是接受此事件的元素
<button onclick="this.style.display='none'">点击删除我</button>
4,在单独情况下,this代表全局变量
<p>在本例中,this引用window对象</p>
<p id="demo"></p>
<script>
var x=this;
document.getElementById('demo').innerHTML=x
</script>
5,在对象方法中,this代表的是对象
var person = {
firstName: "Bill",
lastName : "Gates",
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
换句话说,this.firstName 意味着 this(person)对象的 firstName 属性。
6,显示函数绑定,call() 和 apply() 方法是预定义的 JavaScript 方法。它们都可以用于将另一个对象作为参数调用对象方法。
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"Bill",
lastName: "Gates",
}
person1.fullName.call(person2); // 会返回 "Bill Gates"