4

I have a javascript function which takes a parameter, like:

function getSomething(cat,handler) {

      varURI = 'text'+cat;
      document.write('<p>'+varURI+'</p>');

    }

What I see in the output is:

text[object Object]

How do I get the real textual value of the Object?

3 Answers 3

8

You need to override the toString method of the object -and give your object a "textual value"-.

You are getting "[object Object]" because the inherited Object.prototype.toString method is being executed, for example:

var cat = {
  name: 'Kitten',
  toString: function () {
    return this.name + ' meow';
  }
};

This own toString method will be executed when you make any implicit to string conversion (like when you concatenate a string to it), e.g.:

console.log(cat+' text'); // "Kitten meow text"

Note: If you mean by "textual value" a "string representation" of the object, (e.g. listing property/value pairs), your function will need to enumerate all the properties (using the for-in statement), but usually most of the time, that's done for debugging purposes, if that's the case, I would recommend you to get a debugger (like Firebug), and use the console.dir method.

Sign up to request clarification or add additional context in comments.

Comments

2

I don't know what cat is, but usually you use the toString() method.

function getSomething(cat,handler) {

  varURI = 'text'+cat.toString();
  document.write('<p>'+varURI+'</p>');

}

1 Comment

Actually, he's getting "[object Object]" because the object doesn't have an own toString method (it's executing the inherited one from Object.prototype.toString), calling cat.toString(); without overriding it won't make any difference, e.g.: console.log({}+''); and console.log({}.toString()); both produce "[object Object]".
0

You can make this:

function ObjectToString(input,KeysOnly) {
    var ret = [];
    if(KeysOnly) 
       for(var k in input) 
        ret[k] = input[k]; 
    else 
        for(var k in input) 
        ret.push(k);
    return ret.toString();
}

function getSomething(cat,handler) {

  varURI = 'text'+ObjectToString(cat);
  document.write('<p>'+varURI+'</p>');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.