JavaScript: Why does overriding the toString() method of an object cause chrome to lose the object name in error messages?
-
19-10-2022 - |
Question
Given the code below:
/*Class with overridden toString() */
function Stringy(name){
this.name = name;
}
Stringy.prototype.test = function () {return 'test'};
Stringy.prototype.toString = function () {return 'Stringy'};
/*Class with default toString() */
function NoStringy(name){
this.name = name;
}
NoStringy.prototype.test = function () {return 'test'};
In our Stringy class the instance's toString() works properly when forcing a conversion to string or calling the toString() method. However, the error message displays Object [object Object].
In the NoStringy class the error message has the correct object name, but uses the default Object to string method to identify it's self.
Is there no way to have a custom toString() and get the correct object Class in the error messages? Why would overriding the toString() break this functionality? Could this be a bug?
I'm using Chrome Version 33.0.1750.117 m.
Here is the test or check out the fiddle:
test(new Stringy('Stringy instance'));
test(new NoStringy('NoStrigy instance'));
function test(i){
var name = i.name;
var display = document.getElementById('display');
display.innerHTML += ('<br>----Testing: <i>' + name + '</i>-----<br>');
display.innerHTML += (name + ': ' + i + '<br>');
display.innerHTML += (name + '.toString(): ' + i.toString() + '<br>');
try{
display.innerHTML +=(name+'.foo(): '+i.foo()+'<br>')
}
catch(e){
e = e.message.replace('<', '').replace('>', '');
display.innerHTML +=(name+'.foo(): '+e+'<br>')
}
}
The output is:
----Testing: Stringy instance-----
Stringy instance: **Stringy**
Stringy instance.toString(): Stringy
Stringy instance.foo(): **Object [object Object]** has no method 'foo'
----Testing: NoStrigy instance-----
NoStrigy instance: **[object Object]**
NoStrigy instance.toString(): [object Object]
NoStrigy instance.foo(): **Object #NoStringy** has no method 'foo'
The constructors in both objects point to the proper constructor so the console shows the correct constructor name as well.
console output of each instance:
Stringy {name: "Stringy instance", test: function, toString: function}
- name: "Stringy instance"
- __proto__: Stringy
- constructor: function Stringy(name){
- test: function () {return 'test'}
- toString: function () {return 'Stringy'}
- __proto__: Object
NoStringy {name: "NoStrigy instance", test: function}
- name: "NoStrigy instance"
- __proto__: NoStringy
- constructor: function NoStringy(name){
- test: function () {return 'test'}
- __proto__: Object
I have opened a ticket: https://code.google.com/p/chromium/issues/detail?id=348865
Pas de solution correcte