面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
1、在方法中,this 表示该方法所属的对象。
2、如果单独使用,this 表示全局对象。
3、在函数中,this 表示全局对象。
4、在函数中,在严格模式下,this 是未定义的(undefined)。
5、在事件中,this 表示接收事件的元素。
6、类似 call() 和 apply() 方法可以将 this 引用到任何对象。
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
在对象方法中, this 指向调用它所在方法的对象。在上面一个实例中,this 表示 person 对象。fullName 方法所属的对象就是 person。
单独使用 this,则它指向全局(Global)对象。在浏览器中,window 就是该全局对象为 [object Window]:
var x = this;
在函数中,函数的所属者默认绑定到 this 上。在浏览器中,window 就是该全局对象为 [object Window]:
function myFunction() { return this; }
"use strict"; function myFunction() { return this; }
在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:
<button onclick="this.style.display='none'"> 点我后我就消失了 </button>
下面实例中,this 是 person 对象,person 对象是函数的所有者:
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
PS:this.firstName 表示 this (person) 对象的 firstName 属性。
HTML2020-03-28
HTML2020-03-07
HTML2020-01-24
python2019-11-07
HTML2020-01-26
HTML2020-03-27