2

当我记录类似console.log('' + {});控制台的内容时,Chrome 会打印[Object object],但 node.js 中的内容不同({})。此时我会认为控制台输出取决于执行环境。

然而,最近我发现,给定一些非空对象foo,我以某种方式打印了 Chrome,null而不是上面的预期输出。因此使用console.log('' + foo);导致null控制台。这怎么可能?我的第一个猜测是我一定是不小心覆盖了一些重要的东西,比如某种toString()方法。否则我无法解释为什么 Chrome 会将某些非空对象解释为null将其添加到字符串中。

有谁知道隐式对象到字符串的转换实际上是如何工作的?并不是说这是一个阻碍,但它真的让我想知道。

编辑:我没有包含 JSFiddle,因为这发生在一些依赖非常重的类中,所以没有合适的最小工作示例我可以为您提供。无论如何,这个问题并不涉及我的代码,它是相当基础和技术性的。

另一个编辑:为了完整起见,我添加了我在评论中发布的屏幕截图。

4

2 回答 2

1

既然您询问了对象到字符串的转换:Object.toString

如果您在字符串连接表达式中使用对象,它将调用对象的toString()函数。您可以实现自己的功能,这可能会导致您描述的问题:

function Foo(bar){
  this.bar = bar;
}
Foo.prototype.toString = function fooToString(){
    return this.bar;
};

console.log('' + new Foo(null)); // null

没有看到任何代码,我猜是这个,或者它实际上只是 String "null"。您说您已经检查了该toString功能,但要确保您也可以在运行时使用foo.toString.toSource(). 或者只是通过调试器运行对象并检查它。

于 2013-04-27T02:23:54.187 回答
1

In the first case the difference is simply in how the different environments choose to represent an object as a string in the console. They both mean the same thing, namely that the thing you're logging is an object. You might see a further difference if you tested in the developer tools in Firefox or Safari.

In your second example, I suspect the value of foo is null - I just can't think of a situation in which the statement console.log('' + foo) would print null if the value of foo wasn't set to null or, as Xymostech says in the comments, set to the string null.

于 2013-04-27T01:35:28.167 回答