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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With