我试图在一个非常简单的类中覆盖'toString'方法。我尝试了多种方法,但没有得到我期望的输出
function foo(arg){
this.n=20;
this.x=arg;
}
foo.prototype.toString = function(){
return this.x.toString();
};
c = new foo(5);
console.log(c);
我希望看到输出为“5”,但我得到的输出是默认的“{n:20,x:5}”
我做错了什么?
答案 0 :(得分:4)
只有声明原型才能调用它:
function foo(arg) {
this.n=20;
this.x=arg;
}
foo.prototype.toString = function(){
return this.x.toString();
};
c = new foo(5);
console.log(c.toString());
// ^^^^^^^^^^^----------- the main change is here
答案 1 :(得分:3)
某些浏览器可能会将toString
用于console.log
,但有些浏览器会以更实用的形式显示该值。例如,在Firefox中,您可以获得指向对象属性视图的链接。
如果您在某处使用该对象,则需要使用字符串,它将使用您指定的ToString
方法:
function foo(arg) {
this.n=20;
this.x=arg;
}
foo.prototype.toString = function(){
return this.x.toString();
};
c = new foo(5);
document.write(c);

答案 2 :(得分:1)