0

When I use the String constructor I allways wonder how is it made.It returns the string you specificed as a parameter even though it is instanciated with the "new" operator like :

  var str = new String("Hello World")
  //str == "Hello World"

If I make a constructor and I give it a return value it returns an Object when instanciated :

  function CreateString(st) {
  return ''+st 
  }
  var MyString = new CreateString("Hello there!")
  //MyString == "[Object object]"

How can I create a constructor that returns a value Other than [Object object] ?

Update: I am trying to create a constructor function that has both properties and a value itself like :

   function MyConstructor() {
    this.myMethod = function() {
     return 73
    }
     return 25
   }
    /*I want MyConstructor to have the value 25 and the myMethod method */
   alert(MyConstructor()) // to be 25
   alert(MyConstructor().myMethod()) //to be 73
Alfi Louis
  • 105
  • 1
  • 2
  • 5

2 Answers2

1

You can replace toString() function definition in the desired class.

function CreateString() {
  function toString() { return 'foo' }
}

Example: Number.prototype.toString()

zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Yes. this works. but the constructor itself always returns the object – Michael Ritter Jan 23 '17 at 14:21
  • @MichaelRitter see http://stackoverflow.com/a/6307570/2013580 and http://stackoverflow.com/questions/332422 – zurfyx Jan 23 '17 at 14:32
  • what should those links show me? just because a class has a toString method, the constructor still returns a class instance, not the value of the toString() call (unless you print it, where it automatically calls .toString()) – Michael Ritter Jan 23 '17 at 14:42
0

By this line

var MyString = new CreateString("Hello there!")

you're not simply calling function CreateString, you're creating a new Object of 'type' CreateString (an instance of a function).

I guess what you want is just

var MyString = CreateString("Hello there!")
Eduard Malakhov
  • 1,095
  • 4
  • 13
  • 25