Javascript:在非常简单的类中不能覆盖toString方法?

时间:2015-09-20 14:40:54

标签: javascript console.log

我试图在一个非常简单的类中覆盖'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}”

我做错了什么?

3 个答案:

答案 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)

正如Vicky所说。

或者您可以隐式转换为字符串

console.log(c+'');

这将调用toString方法

fiddle 此处