迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中获取对象的类名

作者:迹忆客 最近更新:2023/03/11 浏览次数:

在面向对象编程中,每当我们定义一个类时,就会在类内部自动创建一个构造函数。它将出现在类中,但不可见。只有当程序员没有明确定义它时才会创建它。此构造函数称为默认构造函数。

我们对理解构造函数很感兴趣,因为构造函数的名称与类名相同。因此,我们很容易在 JavaScript 中使用其构造函数名称来获取对象的类名。

构造函数是默认构造函数还是你创建它(程序员)都没有关系;构造函数的名称将始终与其类名相同。

要创建一个类的对象,我们首先必须调用它的构造函数。调用构造函数后,我们将其引用存储在一个变量中,以便稍后我们可以对该对象做任何我们想做的事情。让我们通过一个例子来理解这一点。

在这里,我们有一个名为 Person 的空类。我们使用 new 关键字创建这个类的一个对象,并调用它的默认构造函数 Person()。然后我们将它存储在一个名为 obj 的变量中。

现在我们已经创建了一个 Person 类的对象,让我们在其构造函数的帮助下获取该对象的类名。

要获取构造函数的名称,我们可以使用 JavaScript 中的内置函数 constructor。它将返回一个函数。要获取特定的类名,我们必须使用 constructor 函数的 name 属性。

这显示在下面的代码片段中。

class Person{
}

var obj = new Person();
console.log(obj.constructor.name);

输出:

Person

你还可以在一个类中创建一个函数,该函数将返回上述 constructor 函数。并且在创建了这个类的一个对象之后,你可以任意调用这个函数并得到那个对象的类名。

这显示在下面的代码片段中。

class Person {
  getClassName() {
    return this.constructor.name;
  }
}

在这里,我们必须使用一个 this 关键字,它将引用正在调用 getClassName() 方法的当前对象并返回其类名。

唯一需要担心的是,如果你正在缩小 JavaScript,构造函数的名称将在缩小后发生变化。如果你调用了 getClassName 函数,它将返回一些其他类名,这些类名将在缩小后出现,而不是 Person

此外,IE9 下不支持 name 属性。这不是一个大问题,因为大多数用户使用 Chrome 和 Firefox 等现代浏览器。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便