如何获取JavaScript对象的类?

JavaScript

斯丁卡卡西

2020-03-11

我创建了一个JavaScript对象,但是如何确定该对象的类呢?

我想要一些类似于Java的.getClass()方法。

第681篇《如何获取JavaScript对象的类?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
梅十三 2020.03.11

这是getClass()的实现getInstance()

您可以使用来获取对象类的引用this.constructor

从实例上下文中:

function A() {
  this.getClass = function() {
    return this.constructor;
  }

  this.getNewInstance = function() {
    return new this.constructor;
  }
}

var a = new A();
console.log(a.getClass());  //  function A { // etc... }

// you can even:
var b = new (a.getClass());
console.log(b instanceof A); // true
var c = a.getNewInstance();
console.log(c instanceof A); // true

从静态上下文:

function A() {};

A.getClass = function() {
  return this;
}

A.getInstance() {
  return new this;
}
蛋蛋蛋蛋 2020.03.11

Javascript是一种无类语言:没有类可以像Java中一样静态地定义类的行为。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。可以使用JavaScript中的原型来模拟许多基于类的功能。

StafanJinJin 2020.03.11

在javascript中,没有任何类,但是我认为您需要构造函数名称,obj.constructor.toString()并将告诉您所需的内容。

小胖MandyGil 2020.03.11

对于ES6中的Javascript类,可以使用object.constructor在下面的示例类中,该getClass()方法将返回您期望的ES6类:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

如果从getClass方法实例化该类,请确保将其包装在方括号中,例如ruffles = new ( fluffy.getClass() )( args... );

前端LEY米亚 2020.03.11

我现在有一种情况可以通用工作,并使用了以下方法:

class Test {
  // your class definition
}

nameByType = function(type){
  return type.prototype["constructor"]["name"];
};

console.log(nameByType(Test));

如果您没有对象的实例,那就是我发现通过类型输入获取类名称的唯一方法。

(用ES2017编写)

点符号也可以

console.log(Test.prototype.constructor.name); // returns "Test" 
Tony神乐 2020.03.11

getClass()JavaScript中没有Java的完全对应版本通常,这是由于JavaScript是基于原型的语言,而不是Java是基于类的语言

根据您的需要getClass(),JavaScript中有几个选项:

一些例子:

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

注意:如果使用Uglify编译代码,它将更改非全局类名。为了防止这种情况,Uglify有一个--mangle参数,可以使用gulpgrunt设置为false

伽罗理查德 2020.03.11

此函数返回"Undefined"未定义的值和"Null"null。
对于所有其他值,CLASSNAME-part是从中提取的[object CLASSNAME],这是使用的结果Object.prototype.toString.call(value)

function getClass(obj) {
  if (typeof obj === "undefined") return "Undefined";
  if (obj === null) return "Null";
  return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}

getClass("")   === "String";
getClass(true) === "Boolean";
getClass(0)    === "Number";
getClass([])   === "Array";
getClass({})   === "Object";
getClass(null) === "Null";
// etc...
斯丁斯丁 2020.03.11

您可以使用构造函数属性获取对创建对象的构造函数的引用

function MyObject(){
}

var obj = new MyObject();
obj.constructor; // MyObject

如果需要在运行时确认对象的类型,则可以使用instanceof运算符:

obj instanceof MyObject // true
GO小胖 2020.03.11
obj.constructor.name

是现代浏览器中的可靠方法。Function.name已在ES6中正式添加到该标准中,从而使其成为符合标准的方法,可将JavaScript对象的“类”作为字符串获取。如果用实例化该对象var obj = new MyClass(),它将返回“ MyClass”。

它将为数字返回“ Number”,为数组返回“ Array”,为函数返回“ Function”,等等。它的行为通常与预期的一样。失败的唯一情况是通过原型创建的对象没有原型Object.create( null ),或者该对象是从匿名定义(未命名)的函数实例化的。

另请注意,如果要压缩代码,则与硬编码类型字符串进行比较是不安全的。例如,而不是检查是否obj.constructor.name == "MyType",而是检查obj.constructor.name == MyType.name或者只是比较构造函数本身,但是这将无法跨DOM边界,因为每个DOM上都有不同的构造函数实例,因此无法在其构造函数上进行对象比较。

用户7049302300 2020.03.11

要获取“伪类”,您可以通过以下方式获取构造函数

obj.constructor

假设constructor在进行继承时正确设置了-这是通过类似以下方式进行的:

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

这两行,以及:

var woofie = new Dog()

woofie.constructor指向Dog请注意,它Dog是一个构造函数,并且是一个Function对象。但是你可以if (woofie.constructor === Dog) { ... }

如果您想以字符串形式获取类名,我发现以下方法运行良好:

http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects

function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

它到达构造函数,将其转换为字符串,并提取构造函数的名称。

请注意,这obj.constructor.name可能效果很好,但不是标准的。它可以在Chrome和Firefox上使用,但不能在IE(包括IE 9或IE 10 RTM)上使用。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android