1

I have a function that returns an object

function a(){
    return {
        b:1,
        c:2
    }
}

doing a().b will successfuly return 1, but I also want to return something else than [object Object] when calling a(). Something like this

function a(){
    return {
        b:1,
        c:2
        toString: 'you got 2 values'
    }
}

would render something like that

alert(a()) // you got 2 values

Is it possible?

Jonathan de M.
  • 9,721
  • 8
  • 47
  • 72
  • possible duplicate of [Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?](http://stackoverflow.com/questions/6307514/is-it-possible-to-override-javascripts-tostring-function-to-provide-meaningfu) – djechlin Dec 05 '13 at 18:18
  • You can overwrite the default toString() method provided by Object to return any string you like for any object (individually) or object class (on the prototype of a parent object). Everywhere where an implicit or explicit conversion to string is performed your toString() method will be used to create that string. – Mörre Dec 05 '13 at 18:19

1 Answers1

3

What you need is to define your class a and add the function toString in it's definition.

function a(){
    var _this = this;
    _this.b = 1;
    _this.c = 2;
    _this.toString =  function(){return 'you got 2 values';};
    return _this;
}

Now you can call the toString function on a directly:

a().toString(); /*executes the function and returns 'you got 2 values'*/

Or you can instance an object from that class d you can call the inner function:

d = new a(); 
d.toString(); /*returns the same value*/
Deni Spasovski
  • 4,004
  • 3
  • 35
  • 52