是否有可能重写JavaScript的toString()函数提供有意义的输出debugging?

当我在我的JavaScript程序中使用console.log()对象时,我只能看到输出[object Object] ,它在确定它是什么对象(甚至是什么types的对象)方面并不是很有帮助。

在C#中,我习惯重写ToString() ,以便能够自定义对象的debugging器表示forms。 有什么类似的,我可以在JavaScript中做?

您也可以在JavaScript中重写toString 。 看例子:

 function Foo() { } // toString override added to prototype of Foo class Foo.prototype.toString = function() { return "[object Foo]"; } var f = new Foo(); alert(f); // popup displays [object Foo] 

请参阅关于如何在JavaScript中确定对象types名称的讨论。

首先覆盖你的对象或原型的toString

 var Foo = function(){}; Foo.prototype.toString = function(){return 'Pity the Foo';}; var foo = new Foo(); 

然后转换为string来查看对象的string表示forms:

 //using JS implicit type conversion console.log('' + foo); 

如果您不喜欢额外的input,则可以创build一个函数,将其参数的string表示logging到控制台:

 var puts = function(){ var strings = Array.prototype.map.call(arguments, function(obj){ return '' + obj; }); console.log.apply(console, strings); }; 

用法:

 puts(foo) //logs 'Pity the Foo' puts(foo, [1,2,3], {a: 2}) //logs 'Pity the Foo 1,2,3 [object Object]' 

更新

E2015为这个东西提供了更好的语法,但是你必须使用像Babel这样的转译器:

 // override `toString` class Foo { toString(){ return 'Pity the Foo'; } } const foo = new Foo(); // utility function for printing objects using their `toString` methods const puts = (...any) => console.log(...any.map(String)); puts(foo); // logs 'Pity the Foo' 

在浏览器JS中获得可debugging输出的简单方法是将对象序列化为JSON。 所以你可以打个电话

 console.log ("Blah: " + JSON.stringify(object)); 

所以举个例子, alert("Blah! " + JSON.stringify({key: "value"})); 用文本Blah! {"key":"value"}产生一个警报Blah! {"key":"value"} Blah! {"key":"value"}

只需重写toString()方法即可。

简单的例子:

 var x = {foo: 1, bar: true, baz: 'quux'}; x.toString(); // returns "[object Object]" x.toString = function () { var s = []; for (var k in this) { if (this.hasOwnProperty(k)) s.push(k + ':' + this[k]); } return '{' + s.join() + '}'; }; x.toString(); // returns something more useful 

当你定义一个新的types时它会更好:

 function X() { this.foo = 1; this.bar = true; this.baz = 'quux'; } X.prototype.toString = /* same function as before */ new X().toString(); // returns "{foo:1,bar:true,baz:quux}" 

如果你正在使用Node,可能值得考虑util.inspect

 var util = require('util') const Point = { x: 1, y: 2, [util.inspect.custom]: function(depth) { return `{ #Point ${this.x},${this.y} }` } } console.log( Point ); 

这将产生:

 { #Point 1,2 } 

当没有检查的版本打印时:

 { x: 1, y: 2 } 

如果对象是由你自己定义的,你总是可以添加一个toString覆盖。

 //Defined car Object var car = { type: "Fiat", model: 500, color: "white", //.toString() Override toString: function() { return this.type; } }; //Various ways to test .toString() Override console.log(car.toString()); console.log(car); alert(car.toString()); alert(car); //Defined carPlus Object var carPlus = { type: "Fiat", model: 500, color: "white", //.toString() Override toString: function() { return 'type: ' + this.type + ', model: ' + this.model + ', color: ' + this.color; } }; //Various ways to test .toString() Override console.log(carPlus.toString()); console.log(carPlus); alert(carPlus.toString()); alert(carPlus); 

使用模板文字 :

 class Foo { toString() { return 'I am foo'; } } const foo = new Foo(); console.log(`${foo}`); // 'I am foo' 

Chrome控制台日志允许您检查对象。

你可以给任何自定义对象自己的toString方法,或者写一个可以调用你正在查看的对象的通用对象,

 Function.prototype.named= function(ns){ var Rx= /function\s+([^(\s]+)\s*\(/, tem= this.toString().match(Rx) || ""; if(tem) return tem[1]; return 'unnamed constructor' } function whatsit(what){ if(what===undefined)return 'undefined'; if(what=== null) return 'null object'; if(what== window) return 'Window object'; if(what.nodeName){ return 'html '+what.nodeName; } try{ if(typeof what== 'object'){ return what.constructor.named(); } } catch(er){ return 'Error reading Object constructor'; } var w=typeof what; return w.charAt(0).toUpperCase()+w.substring(1); } 

如果包含Prototype JavaScript库 ,则可以使用Object.inspect()来获得更有用的表示forms,而不是重写toString()

大多数stream行的框架包括类似的东西。

 A simple format Date function using Javascript prototype, it can be used for your purpose https://gist.github.com/cstipkovic/3983879 : Date.prototype.formatDate = function (format) { var date = this, day = date.getDate(), month = date.getMonth() + 1, year = date.getFullYear(), hours = date.getHours(), minutes = date.getMinutes(), seconds = date.getSeconds(); if (!format) { format = "MM/dd/yyyy"; } format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1')); if (format.indexOf("yyyy") > -1) { format = format.replace("yyyy", year.toString()); } else if (format.indexOf("yy") > -1) { format = format.replace("yy", year.toString().substr(2, 2)); } format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1')); if (format.indexOf("t") > -1) { if (hours > 11) { format = format.replace("t", "pm"); } else { format = format.replace("t", "am"); } } if (format.indexOf("HH") > -1) { format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1')); } if (format.indexOf("hh") > -1) { if (hours > 12) { hours -= 12; } if (hours === 0) { hours = 12; } format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1')); } if (format.indexOf("mm") > -1) { format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1')); } if (format.indexOf("ss") > -1) { format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1')); } return format; };