Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the name of an object type in JavaScript?

Tags:

javascript

oop

For example:

Object.prototype.toString.call(new Date); // [object Date]
Object.prototype.toString.call(new Array); // [object Array]
Object.prototype.toString.call(new Object); // [object Object]

Now consider this:

var PhoneNumber = function(number) {
    this.number = number;
}

I can override the toString() method, but it doesn't really rename the object type. It just kinda fakes it:

PhoneNumber.prototype.toString = function() {
    return '[object PhoneNumber]';
}

new PhoneNumber().toString(); // [object PhoneNumber]

However, l33t h4x0rs know my toString() method is a lie and I'm a n00b:

Object.prototype.toString.call(new PhoneNumber); // [object Object]

What I would like the result to be, regardless of the toString() method being overridden on the prototype:

 Object.prototype.toString.call(new PhoneNumber); // [object PhoneNumber]

Is this possible?

like image 707
Ben Harold Avatar asked Dec 04 '15 22:12

Ben Harold


1 Answers

The ECMAScript 2015 spec defines a well-known Symbol, which can be used to control this behavior: Symbol.toStringTag. Unfortunately no browser currently support it.

Once it is supported, you will be able to use it like this:

PhoneNumber.prototype[Symbol.toStringTag] = 'PhoneNumber';

Which will produce your expected behavior:

new PhoneNumber().toString(); // [object PhoneNumber]
Object.prototype.toString.call(new PhoneNumber); // [object PhoneNumber]
like image 111
Noah Freitas Avatar answered Sep 24 '22 10:09

Noah Freitas