JavaScript this关键词的使用教程

70 阅读4分钟

作者:Vincy。最后修改于2022年9月13日。

JavaScript this关键字是用来引用当前上下文的对象的。如果周围没有上下文,它默认指向窗口的上下文。

通过this关键字,JavaScript还可以引用更多的上下文*。*下面的列表显示了其中的一些。

  • 全局上下文
  • 方法上下文
  • 函数上下文
  • 类上下文
  • 事件上下文

在这些上下文中,JavaScript的this关键字相应地指代了不同的对象。

下面的代码使用'this'关键字在浏览器中打印主分类和子分类的面包屑

快速实例

这个例子在对象的方法中使用'JavaScript this'来读取属性。

<script>
const category = {
  mainCategory: "Gadgets",
  subCategory: "Mobile phones",
  DisplayCategoryTree : function() {
	  return this.mainCategory + " -> " + this.subCategory;
  }
};
document.write(category.DisplayCategoryTree());
</script>

它是如何工作的

使用'this'的行为基于几个因素而变化。下面列出了其中的一些。

  1. 它在动态绑定和显式绑定之间是不同的。
  2. 它在严格和非严格模式下的工作方式不同。
  3. 它基于包围的上下文而变化。
  4. 它根据它们被调用或使用的方式和地点而不同。

一般来说,'this'会表现为动态绑定。JavaScript支持用bind()方法来改变默认值的显式绑定。

如果没有默认值,JavaScript的'this'会在严格模式下返回'undefined'。

JavaScript中 "this "的不同用法

在JavaScript中,使用'this'关键字来指代一个上下文,有不同的使用方法。让我们来看看这些做法中的以下两种。

  1. 为'this'设置默认值。
  2. 箭头功能。

默认情况下,'this'指的是全局上下文。但是,在严格模式下,函数需要一个默认值来使用'this'作为引用。JavaScript类总是处于严格模式,需要对象引用来使用'this'。

JavaScript的箭头函数给出了紧凑的代码。所以我们可以选择它来编写有目的的有限代码。但是,我更喜欢在编码时使用传统的表达方式。

更多使用JavaScript this的例子

本节给出了更多使用 "JavaScript this "关键字的例子。它展示了'this'在不同的场景和背景下如何工作。

它给出了访问一个类或JavaScript const块的属性的代码。

它可以在事件处理中访问HTML元素。它有助于通过JavaScript的 "this "关键字的引用来操作DOM对象。

例1:使用JavaScript call()函数通过this访问对象属性

这个程序将一个对象的属性与另一个对象的方法绑定。它使用JavaScript call()来记录属性与'*this'*对象的引用。

bind-objects-and-get-properties-with-this.html

<script>
const category = {
  DisplayCategoryTree : function() {
	  return this.mainCategory + " -> " + this.subCategory;
  }
};
const categoryData = {
  mainCategory: "Gadgets",
  subCategory: "Mobile phones",
};

console.log(category.DisplayCategoryTree.call(categoryData));
</script>

例2:严格模式下的JavaScriptthis

在严格模式下,JavaScript this关键字指的是全局窗口上下文。但是,在一个函数中,它会返回未定义的结果。

javascript-this in-strict-mode.html

<script>
"use strict";
let obj = this;
// 'this' is 'window' object
console.log(obj);

function getContext() {
  return this;
}
// In strict mode, JavaScript 'this' inside a funtion is 'undefined'
console.log(getContext());
</script>

例3:用这个关键字设置或获取对象的属性

这个例子设置了一个对象的属性。同时,它使用JavaScript的this关键字读取它们。它定义了获取或设置属性的函数。

javascript-getter-setter-with-this-object-html.php

<script>
const Properties = {
    color: "Black",
    size: "Big",
    type: "2D",

    getColor: function() {
        return this.color;
    },
    setColor: function(newColor) {
        this.color = newColor;
    },
    getSize: function() {
        return this.size;
    },
    setSize: function(newSize) {
        this.size = newSize;
    },

    getType: function() {
        return this.type;
    },
    setType: function(newType) {
        this.type = newType;
    }
};
Properties.setColor("White");
Properties.setSize("small");
Properties.setType("3D");

document.write("Color: "+ Properties.getColor()+"<br>");
document.write("Size: "+ Properties.getSize()+"<br>");
document.write("Type: "+ Properties.getType());
</script>

例四:不同语境下的JavaScript this对象

这个脚本记录了不同语境下的 "JavaScript this "对象。该程序创建了两个类,并从它们的构造函数中记录'this'对象。它返回相应的所有者实例并将其记录到开发者控制台。

我之前写过一个关于PHP构造函数和析构函数的类似教程。

从jQuery document.ready()函数中,'this'返回Document:[对象HTMLDocument]

this-in-different-context.php

这个程序在开发者控制台记录了以下内容。这个'this'对象指的是不同的上下文。

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var x = this;
console.log("Default:" + x);

class Cart {
    constructor() {
        console.log("Class:" + this + " of " + this.constructor.name);
    }
}
const cart = new Cart();

class Product {
    constructor() {
        console.log("Class:" + this + " of " + this.constructor.name);
    }
}
const product = new Product();

$(document).ready(function(){
    var x = this;
    console.log("Document:" + x);
});
</script>

例5:事件背景下的JavaScript this关键字

下面的代码包含了带有on-click事件处理程序的HTML按钮。它通过'this'对象来操作按钮元素的样式。这里,JavaScript的this对象指的是按钮元素。

点击事件调用highlight(this)方法。它将在点击时改变按钮的背景颜色

this-in-event-handler.html

<button onclick="highlight(this)">Button</button>
<script>
function highlight(obj) {
  obj.style.backgroundColor = '#0099FF';
}
</script>

例6:使用Arrow函数

请看下面的例子,它创建了一个紧凑的代码来使用'this'获得全局上下文。

它创建了一个由单行代码组成的函数来返回全局对象。这一行使用JavaScript箭头函数来使用'this'。

arrow-function.html

<script>
var getGlobal = (() => this);
console.log(getGlobal());
</script>

总结

我希望你对这个基本的JavaScript概念有一个很好的了解。示例代码指导你如何在JavaScript中使用'this'。

带有事件处理程序和箭头函数的例子返回相关的对象引用。请在评论区告诉我你对这篇文章的宝贵反馈。
下载