节点js重写toString

我想重写我的对象的默认的toString方法,下面是代码和问题:

function test (){ this.code = 0;//later on I will set these this.name = ""; } test.prototype.toString= function(){ return this.name + "\t"+ this.code +" \t "+this.anotherFunction(); } console.log (Lion.toString()); //works correct ie calls my function console.log (Lion); //doesn't call my function. Prints { code: 0, name: 'jack' } 

不会让String被默认调用?

在find我喜欢的答案之前,在Google上find了这个,这是我最终做的:

您可以使用inspect和v8(chrome / nodejs)将使用从console.log()调用:

 function Foo() {} Foo.prototype.inspect = function() { return "[object Foo]"; } console.log(new Foo()); 

不总是。 Chrome浏览器允许您通过console.log()来检查对象(用于debugging目的)。

尝试这个:

 console.log (''+Lion); 

我感兴趣的是如何做到这一点,一旦我看到如何很好地Immutable.js打印出对象:

 var Immutable = require('immutable'); var map = Immutable.Map({ a: 1, b: 2 }); console.log(map); // Map { "a": 1, "b": 2 } 

经过一些源代码扫描后,我发现他们通过添加toStringinspect对象原型的方法来实现它。 以下是基本的想法,或多或less:

 function Map(obj) { this.obj = obj; } Map.prototype.toString = function () { return 'Map ' + JSON.stringify(this.obj); } Map.prototype.inspect = function () { return this.toString(); } 

同时具有toStringinspect方法意味着对象将在节点(使用inspect )中正确注销,并且如果需要(使用toString )将被正确格式化为string。

编辑:这只适用于节点,浏览器仍然会注销该对象。 如果你不想要这个,首先通过调用toString或者将它和另外一个string连接起来,把它转换成一个string: console.log('' + map)

不。向原型中添加东西使其可用,但并不意味着仅仅因为您创build了它所属的对象的实例而被调用。

例如:

 function foo() { var bar = 123; } foo.prototype.show_bar = function() { console.log(this.bar); } var x = new foo(); // does not log anything x.show_bar(); // logs 123 

我认为你的困惑是认为console.log()自动尝试将其参数转换为string。 它不; 它可以输出数组,对象,函数等