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


当前回答

使用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

其他回答

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

使用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

比如你有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));

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

你应该像这样使用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);/ /函数的