Concatenar mi objeto con una cuerda

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!
}

Esta salida 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.

No quiero [object Object] to be output. How can I change what string myObject spits out when being added to a string?

preguntado el 10 de marzo de 12 a las 07:03

2 Respuestas

You should give your objects a toString method that returns the appropriate string. So you just need to rename get_text a toString. You could write it something like this:

var myObject = (function () {
    var text = 'Text I want to concat.';
    return {
      toString : function () { return text }
    };
}());

respondido 10 mar '12, 07:03

Thank you. I just had to change the name of get_text to toString and everything worked. - garth smith

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.";
}

respondido 10 mar '12, 07:03

Thank you. I would vote your answer up but I do not have enough reputation. >.< - garth smith

JavaScript is only superficialmente similar to Java. In reality, it is a what you would make if you took Scheme and Self and the coerced them into something that sort of looked like Java and sort of behaved like Java. But it really is very different--much more functional, dynamically typed, prototype based... - Tikhon Jelvis

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.