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


当前回答

比如你有var obj;

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

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

其他回答

下面是我提出的解决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。

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在什么地方有用是很重要的,但我目前不觉得它与这个讨论有多大关系。不过,我的思想是开放的。:)

更新

准确地说,我认为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

比如你有var obj;

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

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

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

/** * 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));

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