admin管理员组

文章数量:1405170

I'm trying to override the 'toString' method in a very simple class. I've tried multiple approaches, but am not getting the output I would expect

function foo(arg){
    this.n=20;
    this.x=arg;
}

foo.prototype.toString = function(){
    return this.x.toString();
};

c = new foo(5);

console.log(c);

I expect to see the output as "5" but instead the output I get is the default "{ n:20, x:5 }"

What am I doing wrong?

I'm trying to override the 'toString' method in a very simple class. I've tried multiple approaches, but am not getting the output I would expect

function foo(arg){
    this.n=20;
    this.x=arg;
}

foo.prototype.toString = function(){
    return this.x.toString();
};

c = new foo(5);

console.log(c);

I expect to see the output as "5" but instead the output I get is the default "{ n:20, x:5 }"

What am I doing wrong?

Share Improve this question edited Sep 20, 2015 at 14:46 Paul asked Sep 20, 2015 at 14:40 PaulPaul 3,58210 gold badges40 silver badges63 bronze badges 5
  • 4 What is cell? You mean foo? – Tushar Commented Sep 20, 2015 at 14:42
  • 4 console.log doesn't use toString – georg Commented Sep 20, 2015 at 14:43
  • Try alert(c). Or console.log(String(c)). c really is an object, and the console shows you that. – Bergi Commented Sep 20, 2015 at 14:45
  • Use { for function body in function foo(arg)( – Tushar Commented Sep 20, 2015 at 14:45
  • "... the default "{ n:20, x:5 }"" The default toString would have given you "[object Object]", not "{ n:20, x:5 }". – T.J. Crowder Commented Sep 20, 2015 at 14:45
Add a ment  | 

3 Answers 3

Reset to default 4

Only declaring prototype won't work until you call it:

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

Some browser might use toString for console.log, but some show the value in a more usable form. In Firefox for example you get a link to a view of the object properties.

If you use the object somewhere there a string is expected, it will use the ToString method that you specified:

function foo(arg) {
    this.n=20;
    this.x=arg;
}

foo.prototype.toString = function(){
    return this.x.toString();
};

c = new foo(5);

document.write(c);

As Vicky said.

or you can implicitly cast to a string

console.log(c+'');

This will invoke the toString method

fiddle here

本文标签: consolelogJavascript can39t override toString method in very simple classStack Overflow