For the following code:
function F() {
}
// Define class fields for F
F.value = [ 1, 2, 3, 4 ];
console.log('F', F); // F function F() { }
console.log(F); // { [Function: F] value: [ 1, 2, 3, 4 ] }
In the code above, I have define class fields for the constructor F. When I console.log() in node different argument list, the printing result is different for F.
The one is function F() { }, the other is { [Function: F] value: [ 1, 2, 3, 4 ] }. So that's why?
But the output is same in browser console.
My node version is v4.2.6 and linux.
Thanks in advance.
-
1nodejs.org/api/console.html#console_console_log_data_argsMukesh Sharma– Mukesh Sharma2017年06月12日 06:14:37 +00:00Commented Jun 12, 2017 at 6:14
-
Thanks, @MukeshSharma, I'll take a look.zhenguoli– zhenguoli2017年06月12日 06:16:09 +00:00Commented Jun 12, 2017 at 6:16
1 Answer 1
It might be a bug. There's no good reason to differ.
Why does this happen? console.log delegates to util.format (quite literally), and format distinguishes between a string for the first argument (that might be a format string) and something else. You can find the exact algorithm here. Basically:
- when the first argument is a string, placeholders get replaced by the respective values, then further arguments are adjoined. Those are inspected when they are objects or symbols, but just cast to strings and concatenated otherwise.
- when the first argument is not a string, every value is inspected, then they are concatenated together.
Due to the object check relying on typeof, it does not consider functions to be objects, and your function is directly stringified. This difference between casting and inspecting can also be observed for other values (e.g. console.log("0", "example") vs console.log(0, "example")).
1 Comment
console.log(). When I use console.log() in node, I have found some inconsistent output for the same object. So that's so strang to me. And I want to know why.