Constructor function return is other than “[Object object]”

此生再无相见时 提交于 2019-12-25 07:49:21

问题


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

回答1:


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

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

Example: Number.prototype.toString()




回答2:


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!")


来源:https://stackoverflow.com/questions/41808464/constructor-function-return-is-other-than-object-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!