JavaScript 中的 this

92 阅读2分钟

这是我参与8月更文挑战的第16天,活动详情查看:8月更文挑战

前言

吃饱饭才有力气写代码~

今天我们来聊一聊 JavaScript里的 this 这个关键字。以下这些内容借鉴了菜鸟教程相关的知识点,为了自己加深印象。

一.this

面向对象语言中的 this 表示当前对象的一个引用; 在JavaScript中,this会随着执行环境的不同而发生变化, 比如:

  • 单独使用时,this 表示全局对象。
  • 在函数中,this 表示全局对象。
  • 在事件中,this 表示接收时间的元素。
  • 在方法中,this 表示该方法所属的对象。
var person = { 
firstName: "John", 
lastName : "Doe",
id : 5566, 
fullName : function() {
    return this.firstName + " " + this.lastName; 
    } 
};

二.方法中的 this

在对象方法中,this 指向调用它所在方法的对象。 在上面的代码中,this 表示 person 对象。 fullName 方法所属的对象就是 person。

三.单独使用 this

单独使用 this,则它指向全局(Global)对象。
在浏览器中,window 就是该全局对象为 [object Window]

var x = this;

严格模式下,如果单独使用,this 也是指向全局(Global)对象。

"use strict"; 
var x = this;

四.函数中使用 this (默认)

在函数中,函数的所属者默认绑定到 this 上。 在浏览器中,window 就是该全局对象为 [object Window]; 严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。

五.事件中的 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; 
    //return this.firstName + " " + this.lastName;
    //this.firstName 表示 this (person) 对象的 firstName 属性。
    } 
};

七.显示函数绑定

我们都知道在JS中函数也是对象,对象就有相应的方法,这其中的apply 和 call ,这俩函数允许切换函数执行的上下文环境,也就是this绑定的对象。 教程上有个例子很好:

var person1 = { 
fullName: function() {
    return this.firstName + " " + this.lastName; 
    } 
} 
var person2 = { 
firstName:"John", lastName: "Doe", 
} 
person1.fullName.call(person2); // 返回 "John Doe"

在这里写一下,一来加深印象,其次也方便回顾~