问题
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