this 关键字
this无法进行赋值
面向对象语言中 this 表示当前对象的一个引用。
关键词指的是它所属的对象。
在方法中,this 表示该方法所属的对象。
单独使用,this 表示全局对象。
在函数中,this 指的是全局对象。
在函数中,在严格模式下,this 是未定义的(undefined)。
在事件中,this 指的是接收事件的元素。
方法中的 this
在对象方法中, this 指向调用它所在方法的对象。
例如:
var str = {
name: "JavaScript",
age : 18,
function : function() {
return this.name + " " + this.age;
}
};
上面的例子中 this表示 person 对象。
function方法所属的对象就是 str。
单独的 this
单独使用 this,则它指向全局对象
例如:
var x = this;
在浏览器中,window 就是该全局对象为 [object Window];
函数中的 this
在 JavaScript 函数中,函数的拥有者默认绑定 this。
因此,在函数中,this 指的是全局对象 [object Window]。
function demo() {
return this;
}
这时候 this 是 undefined。
事件中的 this
例如:
<button onclick="this.style.display='none'">
点击消失
</button>
this 指向了接收事件的 HTML 元素。
对象方法绑定
例子
var str = {
name: "JavaScript",
age : 18,
function : function() {
return this.name + " " + this.age;
}
};``
this 是 str对象,str 对象是函数的所有者;