@FahadM to JavaScriptEnglish • 4 days ago

How do you get the constructor or class name of an object in JavaScript?

message-square
0
1
How do you get the constructor or class name of an object in JavaScript?
@FahadM to JavaScriptEnglish • 4 days ago

To get the constructor or class name of an object in JavaScript, check value.constructor?.name after guarding against null and undefined (since primitives like null and undefined have no .constructor property), and handle edge cases such as null-prototype objects (Object.create(null)), minified/anonymized classes, or custom Symbol.toStringTag descriptors rather than assuming obj.constructor.name always returns a descriptive, non-empty string.


1. Safe Constructor / Class Name Lookup with Null and Prototype Guards

Validate that value is not null or undefined, safely inspect value.constructor?.name, and fall back cleanly when an object has a null prototype or no named constructor:

// Safely resolve the constructor or class name of any JavaScript value
function getTypeName(value) {
  if (value === null) {
    return "Null";
  }
  if (value === undefined) {
    return "Undefined";
  }

  try {
    const proto = typeof Object.getPrototypeOf === "function" ? Object.getPrototypeOf(value) : null;
    if (proto === null) {
      return "NullPrototypeObject";
    }

    const ctor = value.constructor;
    if (typeof ctor === "function" && typeof ctor.name === "string" && ctor.name.trim().length > 0) {
      return ctor.name;
    }

    const tag = value[Symbol.toStringTag];
    if (typeof tag === "string" && tag.trim().length > 0) {
      return tag.trim();
    }

    return typeof value;
  } catch (error) {
    throw new Error(`Failed to resolve constructor/class name: ${error.message}`);
  }
}

// Example usage:
try {
  class OrderService {}
  const order = new OrderService();
  const dict = Object.create(null);

  console.log(getTypeName(order));     // "OrderService"
  console.log(getTypeName([1, 2]));    // "Array"
  console.log(getTypeName(new Map())); // "Map"
  console.log(getTypeName(dict));      // "NullPrototypeObject"
  console.log(getTypeName(null));      // "Null"
} catch (error) {
  console.error(`${error.name}:${error.message}`);
}
  • Always guard null and undefined first: Accessing null.constructor or undefined.constructor throws a TypeError.
  • Check Object.getPrototypeOf(value) === null before reading .constructor: Objects created with Object.create(null) inherit from null, not Object.prototype, so dict.constructor is undefined.

2. Production Pitfalls: Minification, Anonymous Classes, and Overridden .constructor

In real-world builds and complex object graphs, relying blindly on obj.constructor.name can surprise you:

// Inspect class vs. prototype chain without relying solely on mutable `.constructor`
function inspectPrototypeChain(instance) {
  if (instance === null || (typeof instance !== "object" && typeof instance !== "function")) {
    throw new TypeError("Expected instance to be a non-null object or function.");
  }

  try {
    const chain = [];
    let currentProto = Object.getPrototypeOf(instance);

    while (currentProto !== null) {
      const ctorName =
        currentProto.constructor && typeof currentProto.constructor.name === "string"
          ? currentProto.constructor.name
          : "<anonymous>";
      chain.push(ctorName);
      currentProto = Object.getPrototypeOf(currentProto);
    }

    return chain;
  } catch (error) {
    throw new Error(`Failed inspecting prototype chain: ${error.message}`);
  }
}

// Example usage:
try {
  class BaseWorker {}
  class SyncWorker extends BaseWorker {}
  console.log(inspectPrototypeChain(new SyncWorker())); // ["SyncWorker", "BaseWorker", "Object"]
} catch (error) {
  console.error(`${error.name}:${error.message}`);
}
  • Bundlers/minifiers can mangle or strip class names: Aggressive minification or anonymous class expressions (const C = class {}) can shorten or empty ctor.name.
  • Prefer instanceof or explicit type tags/discriminators for runtime type checks: Never use obj.constructor.name === "MyClass" as a security or protocol check—use instanceof or an explicit kind/type field.

3. Cross-Realm / vm / iframe Nuances and Explicit Class Metadata

When objects cross execution contexts (such as an <iframe> in the browser or a node:vm context in Node.js) or when you want stable names independent of minification, keep cross-realm behavior in mind:

  • Cross-realm instanceof can behave differently from constructor names: An Array or custom class instance created inside another realm has its own realm’s constructor function, even though .constructor.name still reports the class name string.
  • Attach explicit metadata (static readonly kind = ... or a Map registry) when names must survive minification: Relying on runtime Function.prototype.name is helpful for logging/diagnostics, not guaranteed invariant identifiers.
  • Avoid mutating Object.prototype: Modifying shared prototypes can pollute constructor lookups across unrelated objects and libraries.