Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将公共方法附加到原型_Javascript_Oop_Prototype Programming_Public Method - Fatal编程技术网

Javascript 将公共方法附加到原型

Javascript 将公共方法附加到原型,javascript,oop,prototype-programming,public-method,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,

这是我的代码:

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
的实例不足以调用该方法吗?我在这里错过了什么?

应该是
document.write(myQuo.get_status())

更新:

另一个选项是覆盖toString方法,如下所示:

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

@alnorth29--是的,就是这样。我的问题是,既然
get_status()
方法附加到原型上,那么当调用
Quo
的新实例时,它不应该被自动调用吗?它实际上不是这样工作的。该功能将自动添加到Quo的所有实例中,但这并不意味着将实例强制转换为字符串时将运行它。@alnorth29--是否有办法编写代码,以便在新实例中始终调用原型方法?如果希望在将对象强制转换为字符串时返回特定字符串,则可以覆盖对象的toString方法。确定。在您的示例中,您可以简单地将get_status替换为toString。您可以在下面的网站上看到一个正在运行的示例