0

FirstOfAll plz help me provide info of working of valueOf method in different object.

Is there a difference between String.prototype.valueOfand Object.prototype.valueOf method,if there exist difference why not seen when Object.prototype.valueOf.call("maizere").Since valueOf here is the method of Object.prototype not String.protototype but it outputs string rather than [object String].Shouldn't it output [object String]?It seems as if the valueOf method belongs to String.prototype since it outputs string.Thank u for ur help

Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41

1 Answers1

1

The main difference here is between strings and string objects:

> typeof String('foo')
"string"
> typeof new String('foo')
"object"
> "foo" === String('foo')
true
> "foo" === new String('foo')
false
> String.prototype.valueOf.call("maizere")
"maizere"
> Object.prototype.valueOf.call("maizere")
String {0: "m", 1: "a", 2: "i", 3: "z", 4: "e", 5: "r", 6: "e", format: function, truncate: function, splitOnLast: function, contains: function}

String's valueOf returns a string and Object's valueOf returns an object, which in this case is a string object. They aren't the same thing.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • isn't valueOf method of Object.prototype supposed to return [object objectName] ,than why is it returning string object .It should all the time return [object ObjectName] isn't it? – Maizere Pathak.Nepal May 15 '13 at 18:27
  • @Maizere: Open up Chrome's console and try it again. It doesn't return `[object ObjectName]`. – Blender May 15 '13 at 18:28
  • so than shall i consider that If an object has no primitive value only than valueOf returns the object itself, which is displayed as:[object object] else only object – Maizere Pathak.Nepal May 15 '13 at 18:44
  • @Maizere: I'm not sure what you mean. – Blender May 15 '13 at 18:54
  • also why console.log(Object.prototype.valueOf.call([])) outputs blank ?shouldn't it alert[object Object] since it is empty .Reference [here](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/valueOf) – Maizere Pathak.Nepal May 15 '13 at 18:54
  • @Maizere: You have to call `Object.prototype.toString.call(Object.prototype.valueOf.call([]))`. – Blender May 15 '13 at 18:55