在javascript中是否有一种方法可以使运行时在错误消息中使用不同的对象表示.
典型的错误消息
Uncaught TypeError: Object [object Object] has no method 'toggle'
如果我们能够给对象提供更好的表示,那将会很有帮助[object Object].在其他语言中,您可以通过覆盖来打印更好的对象表示toString().
但是,在这种情况下,重写toString似乎没有效果.
oll*_*cua -3
像这样的东西应该有效:
Object.prototype.toString = function() {
return '(OBJECT: ' + this.name + ')';
};
foo = { name: 'foo' };
bar = { name: 'bar' };
baz = {}
foo.thing(); // TypeError: Object (OBJECT: foo) has no method 'thing'
bar.thing(); // TypeError: Object (OBJECT: bar) has no method 'thing'
baz.thing(); // TypeError: Object (OBJECT: undefined) has no method 'thing'
Run Code Online (Sandbox Code Playgroud)
(节点.js)