Change object default toString value in Javascript

For any javascript object, e.g.:

const obj = {
  x : 3,
  y : true,
  z : function() {}
};

A call obj.toString() will by default yield: [object Object] . Some other objects, like the browser Window object, will yield: [object Window] if printed on dev tools.

We can force a value different than [object Object] by executing this:

Object.defineProperty(
  obj, 
  Symbol.toStringTag, 
  { 
    configurable: true,   // if might be changed/redefined.
    value: ‘MyCoolObj’    // put here your object description.
  });

Now, obj will be identified as:

Tagging special objects has never been easier than this.

Addendum

The native side of things would look like this:

// for an existing object or template
object->Set(
      v8::Symbol::GetToStringTag(isolate),
      v8::String::NewFromUtf8(isolate, "YOUR_STRING_CLASS_HERE"),
      static_cast<v8::PropertyAttribute>(
          v8::ReadOnly | v8::DontEnum));

// you also could just (e.g. in interface_template):
a_function_template->SetClassName(
      v8::String::NewFromUtf8(isolate,"YOUR_STRING_CLASS_HERE"));

Published by ibon

Chocolate engineer, software eater. Data visualisation at Workday. Past: Platochat, SdkBox, Chukong, Ludei.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: