-1

Why do the built-in constructors in javascript return a value and not an object?They are called with the new operator and They still do not return an object.How can I create a constructor which doesn't return an object like :

      new Number() //returns 0 instead of [Object object]
      new String() //returns "" 
      new Date() //returns today's date

      function SomeConstructor() {
      return "Value"
      }
      new SomeConstructor() // [Object object]
      SomeConstructor() // returns "Value"

How can I create such a constructor?

Alfi Louis
  • 105
  • 1
  • 2
  • 5
  • You might want to explore this material on JS primitives: https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/ – Eduard Malakhov Jan 24 '17 at 11:59
  • 1
    They DO return a object. it just isn't printing as `[Object object]` because they implement the `toString()` method (which returns the string representation used for printing) – Michael Ritter Jan 24 '17 at 12:01
  • Possible duplicate of [Constructor function return is other than "\[Object object\]"](http://stackoverflow.com/questions/41808464/constructor-function-return-is-other-than-object-object) – Michael Ritter Jan 24 '17 at 12:01

1 Answers1

0

They are indeed objects, you can check with typeof.

To get the subtype you can use Object.prototype.toString

As @Michael Ritter pointed out:

it just isn't printing as [Object object] because they implement the toString() method (which returns the string representation used for printing)

    console.log( typeof new Number()) //object
    console.log( typeof new String()) //object 
    console.log( typeof new Date()) //object
    
    console.log( Object.prototype.toString.call(new Number())) //[object Number]
    console.log( Object.prototype.toString.call(new String())) //[object String] 
    console.log( Object.prototype.toString.call(new Date())) //[object Date]

To answer your second question, just return anything in object form rather than primitive form. The reason can be found here

      function SomeConstructor() {
          return new String("Value");
      }
      console.log(new SomeConstructor(), new SomeConstructor().valueOf());
Community
  • 1
  • 1
sabithpocker
  • 15,274
  • 1
  • 42
  • 75