gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:22:38 26 4
gpt4 key购买 nike

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

我做错了什么?

最佳答案

在调用原型(prototype)之前,只声明原型(prototype)是行不通的:

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

关于Javascript:不能在非常简单的类中覆盖 toString 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com