节点js重写toString

时间:2014-02-15 23:44:20

标签: node.js

我试图覆盖我的对象的默认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 i.e. calls my function
console.log (Lion); //doesn't call my function. Prints { code: 0, name: 'jack' }

默认不调用toString吗?

4 个答案:

答案 0 :(得分:6)

并非总是如此。像Chrome这样的浏览器允许您通过console.log()来检查对象(用于调试目的)。

试试这个:

console.log (''+Lion);

答案 1 :(得分:6)

在找到我喜欢的答案之前,在谷歌上看到了这个,这就是我最终做的事情:

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

function Foo() {}

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

console.log(new Foo());

答案 2 :(得分:2)

没有。向原型中添加内容使其可用,但并不意味着它只是因为您创建了它所属的对象的实例而被调用。

例如:

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()会自动尝试将其参数转换为字符串。它没有;它可以输出数组,对象,函数等。

答案 3 :(得分:2)

一旦我看到Immutable.js打印出来的物品有多好,我对如何做到这一点感兴趣:

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

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

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),并在必要时将其正确格式化为字符串(使用{ {1}})。

编辑:这仅适用于节点,浏览器仍会注销该对象。如果您不想这样做,请先将其转换为字符串,方法是调用toString或将其与另一个字符串连接:toString

相关问题