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 meanfoo
? – Tushar Commented Sep 20, 2015 at 14:42 -
4
console.log
doesn't usetoString
– georg Commented Sep 20, 2015 at 14:43 -
Try
alert(c)
. Orconsole.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 infunction foo(arg)(
– Tushar Commented Sep 20, 2015 at 14:45 -
"... the default
"{ n:20, x:5 }"
" The defaulttoString
would have given you"[object Object]"
, not"{ n:20, x:5 }"
. – T.J. Crowder Commented Sep 20, 2015 at 14:45
3 Answers
Reset to default 4Only 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
版权声明:本文标题:console.log - Javascript: can't override toString method in very simple class? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744288011a2598974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论