将公共方法附加到原型

时间:2011-08-04 16:17:10

标签: javascript oop prototype-programming public-method

这是我的代码:

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);

当我运行此代码时,结果为[object Object]。由于get_status()已附加到Quo prototype,因此不应调用Quo的实例来调用该方法吗?我在这里错过了什么?

1 个答案:

答案 0 :(得分:2)

不应该是document.write(myQuo.get_status());吗?

<强>更新

另一种选择是覆盖toString方法,如下所示:

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