JavaScript中是否有类似Java的class.getName()?
当前回答
你能得到的最接近的是typeof,但它只返回任何自定义类型的“object”。关于这些,请参阅Jason Bunting。
编辑,Jason因为某种原因删除了他的帖子,所以只使用Object的构造函数属性。
其他回答
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在什么地方有用是很重要的,但我目前不觉得它与这个讨论有多大关系。不过,我的思想是开放的。:)
非常简单!
我最喜欢在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
}
您可以使用instanceof操作符来查看一个对象是否是另一个对象的实例,但由于没有类,因此无法获得类名。
下面是一个基于公认答案的实现:
/** * 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));
只有在别无选择时才使用构造函数属性。
更新
准确地说,我认为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