Reputation: 103
This question is for objects in Javascript.
I notice that I can add a string and an Error object just fine, and the Error object text is concatenated with no problems.
try {
throw new Error('Sample Text');
} catch (error) {
document.writeln('There was an error. ' + error); // Go plus sign!
}
This outputs There was an error. Error: Sample Text
which is pretty cool. The Error object knew what string I wanted to concatenate. My own objects do not act nice like this.
var myObject = (function () {
var text = 'Text I want to concat.',
get_text = function () { return text; },
that = {};
that.get_text = get_text;
return that;
}());
document.writeln('What does my object say: ' + myObject); // Uncool
My own object outputs What does my object say: [object Object]
and does not act nice like the Error object does.
I do not want [object Object]
to be output. How can I change what string myObject spits out when being added to a string?
Upvotes: 2
Views: 158
Reputation: 6659
You need to provide a toString() method, as in the Java programming language.
(People are always making such a big deal out of how the languages are different, but really, they share some notable similarities, like this.)
For example, look at this bit of code:
function Apple() {
this.toString = function() {
return "I'm an Apple!"
}
}
var apple = new Apple();
document.write(apple);
For existing objects, you can add a toString method this way:
existingObject.prototype.toString = function() {
return "I am an existing objet.";
}
Upvotes: 1
Reputation: 68152
You should give your objects a toString
method that returns the appropriate string. So you just need to rename get_text
to toString
. You could write it something like this:
var myObject = (function () {
var text = 'Text I want to concat.';
return {
toString : function () { return text }
};
}());
Upvotes: 3