本文介绍了console.log是否调用对象的toString方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据,

另外根据

所以,我的问题是

如果我这样做

str = new String("hello")
console.log(str) //prints the string object but not 'hello'
console.log(""+str) //prints "hello"

因此,在第一种情况下,它只是打印对象(不不要调用 toString()方法。

So, in first case, it simply prints the object (doesn't invoke the toString() method).

但在第二种情况下,它不是强制而是简单打印原始值。为什么会这样?

But in second case, it doesn't coerce but simply print the primitive value. Why is that so?

console.log 调用什么方法来打印对象?

Which method does console.log invokes to print the object?

请注意 - 这不是重复的。

Please note that - this is not a duplicate of this question.

推荐答案

控制台API不是定义的标准API在任何规范中,都是在所有浏览器中实现的东西,因此供应商通常可以自己实现,因为没有标准规范来定义API中任何方法的输出。

Console API is not a standard API that is defined in any specification but is something that is implemented across all browsers, so vendors are usually at their liberty to implement in their own fashion as there's no standard spec to define the output of any methods in API.

除非您检查特定浏览器的Console API的实际实现,否则您永远无法确定。 GitHub上有一个,列出了主要浏览器实现之间的差异。

Unless you check the actual implementation of the Console API for a particular browser, you can never be sure. There's a tracker on GitHub listing the differences between implementation from major browsers.

如果你看一下FF中的实现(可用 - 搜索日志),它有一个评论

If you look at the implementation in FF (available here - search for log), it has a comment below

实际实现检查传递给的参数类型log()并根据它的类型生成不同的表示形式。

The actual implementation checks for the type of argument that is passed to log() and based on it's type, it generates a different representation.

来到你的情况, log()为使用创建的字符串打印两个不同的值literal 表示法和使用 String 构造函数创建的字符串,因为它们是两个不同的类型。正如所述,使用字符串创建文字符号称为 String Primitives ,使用String构造函数创建的字符串称为字符串对象

Coming to your case, log() prints two different values for strings created using literal notation and strings created using String constructor because they are two different types. As explained here, Strings created using literal notation are called String Primitives and strings created using String constructor are called String Objects.

var str1 = 'test';
var str2 = new String('hello');

typeof str1 // prints "string"
typeof str2 // prints "object"

由于类型不同,它们的字符串表示形式在Console API中有所不同。如果你查看FF控制台实现的代码,最后一个语句是

As the types differ, their string representation differs in the Console API. If you go through the code for FF's Console implementation, the last statement is

return "  " + aThing.toString() + "\n";

所以为了回答你的问题,FF中的Console API调用 toString() {undefined,null,object,set,map} 类型之一时,才会在参数上使用/ code>。它并不总是调用 toString() valueOf()方法。我没有检查Chrome的实现,因此我不会对此发表评论。

So to answer your question, Console API in FF calls toString() on the argument only if the argument type is not one of {undefined,null,object,set,map} types. It doesn't always call toString() or valueOf() methods. I didn't check the implementation of Chrome, so I won't comment on that.

这篇关于console.log是否调用对象的toString方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:49