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?
You should give your objects a
toStringmethod that returns the appropriate string. So you just need to renameget_texttotoString. You could write it something like this: