节点js重写toString

kou*_*sha 7 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' }
Run Code Online (Sandbox Code Playgroud)

是不是默认情况下调用toString?

pal*_*nik 6

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

试试这个:

console.log (''+Lion);
Run Code Online (Sandbox Code Playgroud)


Jac*_*ker 6

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

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

function Foo() {}

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

console.log(new Foo());
Run Code Online (Sandbox Code Playgroud)


Jus*_*mey 5

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

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

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

function Map(obj) {
  this.obj = obj;
}
Map.prototype.toString = function () {
  return 'Map ' + JSON.stringify(this.obj);
}
Map.prototype.inspect = function () {
  return this.toString();
}
Run Code Online (Sandbox Code Playgroud)

同时拥有toStringinspect方法意味着对象将在节点中正确注销(使用inspect),并且在必要时将正确格式化为字符串(使用toString)。

编辑:这仅适用于节点,浏览器仍会注销该对象。如果您不想要这样,请首先通过调用toString或将其与另一个字符串连接来将其转换为字符串:console.log('' + map)