Search code examples
javascriptoopprototype-programmingpublic-method

Attaching a public method to a prototype


This is my code:

var Quo = function(string) {            //This creates an object with a 'status' property.
    this.status = string;
};

Quo.prototype.get_status = function() { //This gives all instances of Quo the 'get_status' method, 
                                        //which returns 'this.status' by default, unless another 
                                        //instance rewrites the return statement.
    return this.status;
};

var myQuo = new Quo("confused");        //the `new` statement creates an instance of Quo().

document.write(myQuo);

When I run this code the result is [object Object]. Since get_status() is attached to the Quo prototype, shouldn't calling the instance of Quo be enough to invoke the method? What have I missed here?


Solution

  • Shouldn't it be document.write(myQuo.get_status());?

    Update:

    The other option is to overwrite the toString method like so:

    Quo.prototype.toString = function() {
        return this.status;
    };