1

With this:

console.log(String.prototype);

Chrome logs out:

String{}

With this:

console.log(String);

Chrome logs out:

function String(){ [native code] }

Since both String{} and String() gets the same name, why console.log(String) choose the function instead the object?

Lion
  • 18,729
  • 22
  • 80
  • 110
igonejack
  • 2,366
  • 20
  • 29
  • As answered already; the constructor function and the constructor function's prototype are not the same thing. For more information about constructor functions and prototype you can check this answer: http://stackoverflow.com/a/16063711/1641941 – HMR Dec 09 '13 at 07:40

2 Answers2

3

Since both String{} and String() gets the same name, why console.log(String) choose the function instead the object?

For obvious reasons: String is a function and String.prototype is an object. It would be rather confusing if Chrome would generate the same output for those two different values/data types.

For functions, Chrome actually shows the implementation of the function (func.toString()). Some functions are not implemented in JavaScript but in native code and hence you see [native code] instead.

For objects, Chrome takes the name of the function (if available) referred to by the constructor property of the object. The value of String.prototype.constructor is String.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • thanks, so an object just have no it's own name? like primitive values? – igonejack Dec 09 '13 at 04:04
  • In general yes. Only functions can have names. – Felix Kling Dec 09 '13 at 04:07
  • 1
    @igonejack—Ojbects in JavaScript don't have names (Functions are Objects too), but you can assign a reference to an Object to a variable or named property of an object. So an Object can have as many names as you like, or none at all. `var a={};var b=a`. An object with two "names". `(function(){alert('hey')}())`. A function Ojbect with no name. – RobG Dec 09 '13 at 04:18
0

String is the constructor (a function), String.prototype is, unsurprisingly, the prototype for the String class ({} in this case)

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • I see, you mean String in String{} isn't the name of the object but the "class", right? And the objects don't have that kind of name like functions do? – igonejack Dec 10 '13 at 08:30