JavaScript中是否有类似Java的class.getName()?


JavaScript中是否有类似Java的class.getName()?

No.

ES2015更新:类Foo{}的名字是Foo.name。对象的类名,不管它的类型是什么,都是thing。constructor。name。ES2015环境中的内置构造函数具有正确的name属性;例如(2).constructor.name为“Number”。


但这里有各种各样的技巧,都以这样或那样的方式失败了:

这里有一个hack,可以做你所需要的-注意它修改对象的原型,这是人们不喜欢的(通常有很好的理由)

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};

现在,所有对象都将具有getName()函数,该函数将以字符串形式返回构造函数的名称。我已经在FF3和IE7中测试了这个功能,我不能说其他的实现。

如果你不想这样做,这里有一个关于JavaScript中确定类型的各种方法的讨论……


我最近更新了这篇文章,使之更加详尽,尽管它还远远不够。修正欢迎…

使用构造函数属性…

每个对象的构造函数属性都有一个值,但它可能有用,也可能没用,这取决于该对象是如何构造的,以及您想对该值做什么。

一般来说,你可以使用constructor属性来测试对象的类型,如下所示:

var myArray = [1,2,3];
(myArray.constructor == Array); // true

所以,这足以满足大多数需求。也就是说……

警告

在很多情况下根本不起作用

这种模式虽然被打破了,但很常见:

function Thingy() {
}
Thingy.prototype = {
    method1: function() {
    },
    method2: function() {
    }
};

通过new Thingy构造的对象将有一个指向Object的构造函数属性,而不是指向Thingy。所以我们从一开始就堕落了;您根本不能信任您无法控制的代码库中的构造函数。

多重继承

一个不那么明显的例子是使用多重继承:

function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a

现在的事情并不像你想象的那样:

var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true

因此,如果您测试的对象有一个不同的对象集作为原型,您可能会得到意想不到的结果。在本文讨论的范围之外,还有一些方法可以解决这个问题。

构造函数属性还有其他用途,其中一些很有趣,另一些就不那么重要了;现在我们将不深入研究这些用途,因为它与本文的讨论无关。

将不会工作交叉框架和交叉窗口

当你想检查来自不同窗口对象(比如iframe或弹出窗口)的对象类型时,使用.constructor进行类型检查将会失效。这是因为在每个“窗口”中,每个核心类型构造函数都有不同的版本。

iframe.contentWindow.Array === Array // false

使用instanceof操作符…

instanceof操作符也是一种简洁的测试对象类型的方法,但它也有自己的潜在问题,就像构造函数属性一样。

var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true

但是instanceof对文字值不起作用(因为文字不是对象)

3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false

例如,为了使instanceof工作,字面量需要包装在Object中

new Number(3) instanceof Number // true

.constructor检查可以很好地检查字面量,因为。方法调用隐式地将字面量包装在各自的对象类型中

3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true

为什么3是两个点?因为Javascript将第一个点解释为小数点;)

将不会工作交叉框架和交叉窗口

Instanceof也不能跨不同的窗口工作,原因与构造函数属性检查相同。


使用构造函数属性的name属性…

在许多情况下根本不工作

再次,见上文;构造函数完全错误和无用是很常见的。

不工作在<IE9

使用myObjectInstance.constructor.name将为您提供一个包含所使用的构造函数名称的字符串,但要遵守前面提到的关于构造函数属性的警告。

对于IE9及以上版本,你可以通过猴子补丁来支持:

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1] : "";
        },
        set: function(value) {}
    });
}

文章的更新版本。这是在文章发表3个月后添加的,这是文章作者Matthew Scharley推荐使用的版本。这一更改的灵感来自于指出先前代码中潜在缺陷的注释。

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s([^(]{1,})\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1].trim() : "";
        },
        set: function(value) {}
    });
}

使用Object.prototype.toString

正如这篇文章所详述的那样,你可以使用Object.prototype.toString——toString的低级通用实现——来获取所有内置类型的类型

Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]

可以编写一个简短的辅助函数,例如

function type(obj){
    return Object.prototype.toString.call(obj).slice(8, -1);
}

来删除杂项,只得到类型名

type('abc') // String

但是,对于所有用户定义的类型,它将返回Object。


警告所有人…

所有这些都受制于一个潜在的问题,那就是问题中的物体是如何构造的。下面是构建对象的各种方法,以及不同类型检查方法将返回的值:

// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // true
(obj.constructor.name == "Foo");  // true

// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // false
(obj.constructor.name == "Foo");  // false


// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object);              // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == "");         // true


// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object);      // true
(obj instanceof Foo);         // true
(obj.constructor == Foo);     // true
(obj.constructor.name == ""); // true


// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object);            // true
(obj.constructor == Object);        // true
(obj.constructor.name == "Object"); // true

虽然在这组示例中并不是所有的排列都有,但希望这些排列足以让您了解根据您的需要,事情可能会变得多么混乱。不要做任何假设,如果你不能确切地理解你想要的是什么,你可能会在你意想不到的地方导致代码崩溃,因为你没有发现其中的微妙之处。

注意:

对typeof操作符的讨论似乎是一个明显的遗漏,但它在帮助确定对象是否为给定类型方面确实没有用处,因为它非常简单。理解typeof在什么地方有用是很重要的,但我目前不觉得它与这个讨论有多大关系。不过,我的思想是开放的。:)


您可以使用instanceof操作符来查看一个对象是否是另一个对象的实例,但由于没有类,因此无法获得类名。


Jason Bunting的回答给了我足够的线索,让我找到我需要的东西:

<<Object instance>>.constructor.name

例如,在下面这段代码中:

function MyObject() {}
var myInstance = new MyObject();

myinstance。constructor.name将返回"MyObject"。


你能得到的最接近的是typeof,但它只返回任何自定义类型的“object”。关于这些,请参阅Jason Bunting。

编辑,Jason因为某种原因删除了他的帖子,所以只使用Object的构造函数属性。


您可以使用“instanceof”操作符来确定一个对象是否是某个类的实例。如果不知道对象类型的名称,可以使用它的构造函数属性。对象的构造函数属性是对用于初始化对象的函数的引用。例子:

function Circle (x,y,radius) {
    this._x = x;
    this._y = y;
    this._radius = raduius;
}
var c1 = new Circle(10,20,5);

现在c1。构造函数是Circle()函数的引用。 也可以使用typeof操作符,但typeof操作符显示的信息有限。一种解决方案是使用Object全局对象的toString()方法。例如,如果你有一个对象,比如myObject,你可以使用全局对象的toString()方法来确定myObject类的类型。用这个:

Object.prototype.toString.apply(myObject);

我用了一个小技巧:

function Square(){
    this.className = "Square";
    this.corners = 4;
}

var MySquare = new Square();
console.log(MySquare.className); // "Square"

可以时使用constructor.name,不能时使用regex function。

Function.prototype.getName = function(){
  if (typeof this.name != 'undefined')
    return this.name;
  else
    return /function (.+)\(/.exec(this.toString())[1];
};

更新

准确地说,我认为OP要求一个检索特定对象的构造函数名称的函数。在Javascript中,object没有类型,但它本身就是一种类型。但是,不同的对象可以有不同的构造函数。

Object.prototype.getConstructorName = function () {
   var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();
   var cname = str.match(/function\s(\w*)/)[1];
   var aliases = ["", "anonymous", "Anonymous"];
   return aliases.indexOf(cname) > -1 ? "Function" : cname;
}

new Array().getConstructorName();  // returns "Array"
(function () {})().getConstructorName(); // returns "Function"

 


注意:下面的示例已弃用。

一篇由Christian Sciberras链接的博客文章提供了一个如何做到这一点的好例子。也就是说,通过扩展Object原型:

if (!Object.prototype.getClassName) {
    Object.prototype.getClassName = function () {
        return Object.prototype.toString.call(this).match(/^\[object\s(.*)\]$/)[1];
    }
}

var test = [1,2,3,4,5];

alert(test.getClassName()); // returns Array

下面是我提出的解决instanceof缺点的解决方案。它可以从跨窗口和跨框架检查对象的类型,并且在基本类型方面没有问题。

function getType(o) {
    return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1];
}
function isInstance(obj, type) {
    var ret = false,
    isTypeAString = getType(type) == "String",
    functionConstructor, i, l, typeArray, context;
    if (!isTypeAString && getType(type) != "Function") {
        throw new TypeError("type argument must be a string or function");
    }
    if (obj !== undefined && obj !== null && obj.constructor) {
        //get the Function constructor
        functionConstructor = obj.constructor;
        while (functionConstructor != functionConstructor.constructor) {
            functionConstructor = functionConstructor.constructor;
        }
        //get the object's window
        context = functionConstructor == Function ? self : functionConstructor("return window")();
        //get the constructor for the type
        if (isTypeAString) {
            //type is a string so we'll build the context (window.Array or window.some.Type)
            for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) {
                context = context[typeArray[i]];
            }
        } else {
            //type is a function so execute the function passing in the object's window
            //the return should be a constructor
            context = type(context);
        }
        //check if the object is an instance of the constructor
        if (context) {
            ret = obj instanceof context;
            if (!ret && (type == "Number" || type == "String" || type == "Boolean")) {
                ret = obj.constructor == context
            }
        }
    }
    return ret;
}

isInstance需要两个参数:一个对象和一个类型。它工作的真正技巧是检查对象是否来自同一个窗口,如果不是,则获取对象的窗口。

例子:

isInstance([], "Array"); //true
isInstance("some string", "String"); //true
isInstance(new Object(), "Object"); //true

function Animal() {}
function Dog() {}
Dog.prototype = new Animal();

isInstance(new Dog(), "Dog"); //true
isInstance(new Dog(), "Animal"); //true
isInstance(new Dog(), "Object"); //true
isInstance(new Animal(), "Dog"); //false

type参数也可以是返回构造函数的回调函数。回调函数将接收一个参数,该参数是所提供对象的窗口。

例子:

//"Arguments" type check
var args = (function() {
    return arguments;
}());

isInstance(args, function(w) {
    return w.Function("return arguments.constructor")();
}); //true

//"NodeList" type check
var nl = document.getElementsByTagName("*");

isInstance(nl, function(w) {
    return w.document.getElementsByTagName("bs").constructor;
}); //true

需要记住的一件事是IE < 9没有提供所有对象的构造函数,因此上面的NodeList测试将返回false,而且isInstance(alert,“Function”)也将返回false。


使用Object.prototype.toString

正如这篇文章所详述的那样,你可以使用Object.prototype.toString——toString的低级通用实现——来获取所有内置类型的类型

Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]

可以编写一个简短的辅助函数,例如

function type(obj){
    return Object.prototype.toString.call(obj]).match(/\s\w+/)[0].trim()
}

return [object String] as String
return [object Number] as Number
return [object Object] as Object
return [object Undefined] as Undefined
return [object Function] as Function

Agave.JS中的kind()函数将返回:

继承树中最接近的原型 对于'null'和'undefined'等始终为原始类型的类型,则为原始名称。

它适用于所有JS对象和原语,不管它们是如何创建的,并且没有任何惊喜。

var kind = function(item) {
        var getPrototype = function(item) {
            return Object.prototype.toString.call(item).slice(8, -1);
        };
        var kind, Undefined;
        if (item === null ) {
            kind = 'null';
        } else {
            if ( item === Undefined ) {
                kind = 'undefined';
            } else {
                var prototype = getPrototype(item);
                if ( ( prototype === 'Number' ) && isNaN(item) ) {
                    kind = 'NaN';
                } else {
                    kind = prototype;
                }
            }
        }
        return kind;
    };

例子:

数字

kind(37) === 'Number'
kind(3.14) === 'Number'
kind(Math.LN2) === 'Number'
kind(Infinity) === 'Number'
kind(Number(1)) === 'Number'
kind(new Number(1)) === 'Number'

NaN

kind(NaN) === 'NaN'

字符串

kind('') === 'String'
kind('bla') === 'String'
kind(String("abc")) === 'String'
kind(new String("abc")) === 'String'

布尔值

kind(true) === 'Boolean'
kind(false) === 'Boolean'
kind(new Boolean(true)) === 'Boolean'

数组

kind([1, 2, 4]) === 'Array'
kind(new Array(1, 2, 3)) === 'Array'

对象

kind({a:1}) === 'Object'
kind(new Object()) === 'Object'

日期

kind(new Date()) === 'Date'

功能

kind(function(){}) === 'Function'
kind(new Function("console.log(arguments)")) === 'Function'
kind(Math.sin) === 'Function'

未定义的

kind(undefined) === 'undefined'

null

kind(null) === 'null'

其实我也在找类似的东西,然后遇到了这个问题。下面是我如何获得类型:jsfiddle

var TypeOf = function ( thing ) {

    var typeOfThing = typeof thing;

    if ( 'object' === typeOfThing ) {

        typeOfThing = Object.prototype.toString.call( thing );

        if ( '[object Object]' === typeOfThing ) {

            if ( thing.constructor.name ) {
                return thing.constructor.name;
            } 

            else if ( '[' === thing.constructor.toString().charAt(0) ) {
                typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
            } 

            else {

                typeOfThing = thing.constructor.toString().match( /function\s*(\w+)/ );

                if ( typeOfThing ) { 
                    return typeOfThing[1];
                } 

                else {
                    return 'Function';
                }
            }
        } 

        else {
            typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
        }
    }

    return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1);
}

如果有人正在寻找使用jQuery的解决方案,这里是调整后的wiki代码(原来打破了jQuery)。

Object.defineProperty(Object.prototype, "getClassName", {
    value: function() {
        var funcNameRegex = /function (.{1,})\(/;
        var results = (funcNameRegex).exec((this).constructor.toString());
        return (results && results.length > 1) ? results[1] : "";
    }
});

Lodash有很多isMethods,所以如果你在使用Lodash,可能像这样的mixin会很有用:

  // Mixin for identifying a Javascript Object

  _.mixin({
      'identify' : function(object) {
        var output;
          var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments', 
              'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber', 
              'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']

          this.each(isMethods, function (method) {
              if (this[method](object)) {
                output = method;
                return false;
              }
          }.bind(this));
      return output;
      }
  });

它为lodash添加了一个名为“identify”的方法,其工作原理如下:

console.log(_.identify('hello friend'));       // isString

砰砰作响: http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN


好吧,伙计们,我一直在慢慢地建立一个catch all方法,这已经有几年了,哈哈!诀窍是:

有一个创建类的机制。 有一种机制来检查所有用户创建的类、原语和由本地构造函数创建/生成的值。 有一种机制可以将用户创建的类扩展为新的类,这样上述功能就可以渗透到你的代码/应用程序/库等中。

举个例子(或者看看我是如何处理这个问题的),看看github上的以下代码:https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js并搜索:

名为= classOf class sofis =,和或 defineSubClass =(不带反撇号('))。

As you can see I have some mechanisms in place to force classOf to always give me the classes/constructors type name regardless of whether it is a primitive, a user defined class, a value created using a native constructor, Null, NaN, etc.. For every single javascript value I will get it's unique type name from the classOf function. In addition I can pass in actual constructors into sjl.classOfIs to check a value's type in addition to being able to pass in it's type name as well! So for example:

' ' ' //请原谅长命名空间!直到用了一段时间后,我才知道它的影响(它们太糟糕了,哈哈)

var SomeCustomClass = sjl.package.stdlib.Extendable.extend({
    constructor: function SomeCustomClass () {},
    // ...
}),

HelloIterator = sjl.ns.stdlib.Iterator.extend( 
    function HelloIterator () {}, 
    { /* ... methods here ... */ },
    { /* ... static props/methods here ... */ }
),

helloIt = new HelloIterator();

sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`
sjl.classOfIs(helloIt, HelloIterator) === true; // `true`

var someString = 'helloworld';

sjl.classOfIs(someString, String) === true; // `true`

sjl.classOfIs(99, Number) === true; // true

sjl.classOf(NaN) === 'NaN'; // true

sjl.classOf(new Map()) === 'Map';
sjl.classOf(new Set()) === 'Set';
sjl.classOfIs([1, 2, 4], Array) === true; // `true`

// etc..

// Also optionally the type you want to check against could be the type's name
sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!
sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!

```

如果您有兴趣阅读更多关于我如何使用上面提到的设置,请查看repo: https://github.com/elycruz/sjljs

还有关于这个主题的书籍: - Stoyan Stefanov的《JavaScript模式》 - David Flanagan的《Javascript - The Definitive Guide》 ——还有其他很多人…(搜索le’web)。

你也可以快速测试我在这里谈论的功能: - http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (url中的0.5.18路径也有来自github的源代码,减去node_modules等)。

编码快乐!


下面是一个基于公认答案的实现:

/** * Describes the type of a variable. */ class VariableType { type; name; /** * Creates a new VariableType. * * @param {"undefined" | "null" | "boolean" | "number" | "bigint" | "array" | "string" | "symbol" | * "function" | "class" | "object"} type the name of the type * @param {null | string} [name = null] the name of the type (the function or class name) * @throws {RangeError} if neither <code>type</code> or <code>name</code> are set. If <code>type</code> * does not have a name (e.g. "number" or "array") but <code>name</code> is set. */ constructor(type, name = null) { switch (type) { case "undefined": case "null": case "boolean" : case "number" : case "bigint": case "array": case "string": case "symbol": if (name !== null) throw new RangeError(type + " may not have a name"); } this.type = type; this.name = name; } /** * @return {string} the string representation of this object */ toString() { let result; switch (this.type) { case "function": case "class": { result = "a "; break; } case "object": { result = "an "; break; } default: return this.type; } result += this.type; if (this.name !== null) result += " named " + this.name; return result; } } const functionNamePattern = /^function\s+([^(]+)?\(/; const classNamePattern = /^class(\s+[^{]+)?{/; /** * Returns the type information of a value. * * <ul> * <li>If the input is undefined, returns <code>(type="undefined", name=null)</code>.</li> * <li>If the input is null, returns <code>(type="null", name=null)</code>.</li> * <li>If the input is a primitive boolean, returns <code>(type="boolean", name=null)</code>.</li> * <li>If the input is a primitive number, returns <code>(type="number", name=null)</code>.</li> * <li>If the input is a primitive or wrapper bigint, returns * <code>(type="bigint", name=null)</code>.</li> * <li>If the input is an array, returns <code>(type="array", name=null)</code>.</li> * <li>If the input is a primitive string, returns <code>(type="string", name=null)</code>.</li> * <li>If the input is a primitive symbol, returns <code>(type="symbol", null)</code>.</li> * <li>If the input is a function, returns <code>(type="function", name=the function name)</code>. If the * input is an arrow or anonymous function, its name is <code>null</code>.</li> * <li>If the input is a function, returns <code>(type="function", name=the function name)</code>.</li> * <li>If the input is a class, returns <code>(type="class", name=the name of the class)</code>. * <li>If the input is an object, returns * <code>(type="object", name=the name of the object's class)</code>. * </li> * </ul> * * Please note that built-in types (such as <code>Object</code>, <code>String</code> or <code>Number</code>) * may return type <code>function</code> instead of <code>class</code>. * * @param {object} value a value * @return {VariableType} <code>value</code>'s type * @see <a href="http://stackoverflow.com/a/332429/14731">http://stackoverflow.com/a/332429/14731</a> * @see isPrimitive */ function getTypeInfo(value) { if (value === null) return new VariableType("null"); const typeOfValue = typeof (value); const isPrimitive = typeOfValue !== "function" && typeOfValue !== "object"; if (isPrimitive) return new VariableType(typeOfValue); const objectToString = Object.prototype.toString.call(value).slice(8, -1); // eslint-disable-next-line @typescript-eslint/ban-types const valueToString = value.toString(); if (objectToString === "Function") { // A function or a constructor const indexOfArrow = valueToString.indexOf("=>"); const indexOfBody = valueToString.indexOf("{"); if (indexOfArrow !== -1 && (indexOfBody === -1 || indexOfArrow < indexOfBody)) { // Arrow function return new VariableType("function"); } // Anonymous and named functions const functionName = functionNamePattern.exec(valueToString); if (functionName !== null && typeof (functionName[1]) !== "undefined") { // Found a named function or class constructor return new VariableType("function", functionName[1].trim()); } const className = classNamePattern.exec(valueToString); if (className !== null && typeof (className[1]) !== "undefined") { // When running under ES6+ return new VariableType("class", className[1].trim()); } // Anonymous function return new VariableType("function"); } if (objectToString === "Array") return new VariableType("array"); const classInfo = getTypeInfo(value.constructor); return new VariableType("object", classInfo.name); } function UserFunction() { } function UserClass() { } let anonymousFunction = function() { }; let arrowFunction = i => i + 1; console.log("getTypeInfo(undefined): " + getTypeInfo(undefined)); console.log("getTypeInfo(null): " + getTypeInfo(null)); console.log("getTypeInfo(true): " + getTypeInfo(true)); console.log("getTypeInfo(5): " + getTypeInfo(5)); console.log("getTypeInfo(\"text\"): " + getTypeInfo("text")); console.log("getTypeInfo(userFunction): " + getTypeInfo(UserFunction)); console.log("getTypeInfo(anonymousFunction): " + getTypeInfo(anonymousFunction)); console.log("getTypeInfo(arrowFunction): " + getTypeInfo(arrowFunction)); console.log("getTypeInfo(userObject): " + getTypeInfo(new UserClass())); console.log("getTypeInfo(nativeObject): " + getTypeInfo(navigator.mediaDevices.getUserMedia));

只有在别无选择时才使用构造函数属性。


比如你有var obj;

如果你只想知道obj的类型名称,比如“Object”、“Array”或“String”, 你可以用这个:

Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');

你应该像这样使用somevar.constructor.name:

const getVariableType = a => a.constructor.name. tolowercase (); const d = new Date(); const res = getVariableType(d);/ /“日期” Const num = 5; const res2 = getVariableType(num);/ /“数量” Const fn = () => {}; const res3 = getVariableType(fn);/ /函数的 console.log (res1);/ /“日期” console.log(它);/ /“数量” console.log (res3);/ /函数的


使用class.name。这也适用于function.name。

class TestA {}
console.log(TestA.name); // "TestA"

function TestB() {}
console.log(TestB.name); // "TestB"

非常简单!

我最喜欢在JS中获取任何类型的方法

function getType(entity){
    var x = Object.prototype.toString.call(entity)
    return x.split(" ")[1].split(']')[0].toLowerCase()
}

我最喜欢的检查JS中任何类型的方法

function checkType(entity, type){
    return getType(entity) === type
}

对于那些读到这篇文章,想要一个相当有效且经过测试的简单解决方案的人:

const getTypeName = (thing) => {
  const name = typeof thing
  if (name !== 'object') return name
  if (thing instanceof Error) return 'error'
  if (!thing) return 'null'
  return ({}).toString.call(thing).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

要深入了解其工作原理,请签出Array.isArray()的polyfill文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#polyfill