JavaScript this 关键词

this是什么呢?

JavaScript this 关键词指的是它所属的对象。

它拥有不同的值,具体取决于它所使用的位置:

  • 在方法中,this 指的是所有者对象。
  • 单独的情况下,this 指的是全局对象。
  • 在函数中,严格模式下,this 是undefined。
  • 在事件中,this 指的是接受时间的元素。

方法中的this

在对象方法中,this 指的是此方法的”拥有者“

1 var person = {
2   firstName: "Bill",
3   lastName : "Gates",
4   id       : 678,
5   fullName : function() {
6     return this.firstName + " " + this.lastName;  //返回 Bill Gates
7   }
8 };

上面的 this 指的就是person 对象。

因为person 对象是fullName 方法的拥有者。

单独的this

在单独使用时,拥有者是全局对象,因此 this 指的是全局对象。

在浏览器窗口中,全局对象是 [object Window]

1 var x = this; //[object Window]

在严格模式中,如果单独使用,那么 this 指的是全局对象 [object Window]

1 "use strict";
2 var x = this; //[object Window]

函数中的 this (默认)

在JavaScript 函数中,函数的拥有者默认绑定 this 。意思就是如果这个函数不在任何一个对象中,单独存在话,那么其拥有者就是浏览器啦,那么其内如果用到了 this 这个 this 指的就是 [objiect Window]

1 function myFunction() {
2   return this;
3 }

函数中的 this (严格模式)

JavaScript 严格模式不允许默认绑定。(至于什么是严格模式,可以参考W3school 专题 严格模式讲解)

在函数中使用时,在严格模式下, this 是未定义的 (undefined)。

1 "use strict";
2 function myFunction() {
3   return this;  //undefined
4 }

事件处理程序中的 this

在 HTML 事件处理程序中, this 指的是接受此事件的 HTML 元素

1 <button onclick="this.style.display='none'">
2   点击来删除我!
3 </button>

上面的 this 指的就是其所在的 button 元素

对象方法绑定

1 var person = {
2   firstName  : "Bill",
3   lastName   : "Gates",
4   id         : 678,
5   myFunction : function() {
6     return this;  //[object Object]
7   }

上面中的 this 会自动绑定 person 这个对象,也就是说 this 是 person 对象 (person 对象是该函数的"拥有者")

1 var person = {
2   firstName: "Bill",
3   lastName : "Gates",
4   id       : 678,
5   fullName : function() {
6     return this.firstName + " " + this.lastName;  //Bill Gates
7   }

上面的, this.firstName 意味着 this (person)对象的firstName 属性,相当于 person.firstName.

以上内容均在W3school 的 JS this 专题有讲解,参考地址:https://www.w3school.com.cn/js/js_this.asp

猜你喜欢

转载自www.cnblogs.com/ljfsmile0613/p/13183828.html