Does console.log invokes toString method of an object?

只谈情不闲聊 提交于 2019-11-27 14:59:18

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.

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.

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

A multi line stringification of an object, designed for use by humans

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.

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"

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";

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(str) calls str.valueOf() I guess. From JavaScript- The Definitive Guide Its job is to convert an object to a primitive value. The valueOf() method is invoked automatically when an object is used in a numeric context, with arithmetic operators (other than +) and with the relational operators, for example. Most objects do not have a reasonable primitive representation and do not define this method.

---edit----Sorry,copy the wrong line, I mean the ""+str,since there's a type converting

It does not utilize toString, you can do something like this

clog = function(msg){console.log(msg.toString());}
clog(myObj);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!