[英]Override of prototype.toString() is not working in OOP function
[英]Overriding prototype.toString doesn't work
我有以下代码。
function Test() {
this.myTest = "Test";
}
Test.prototype.toString = function testToString() {
return this.myTest;
};
var test = new Test();
console.log(test);
我希望它可以打印Test
,但是它可以打印Test { myTest: 'Test' }
。 我认为重写toString
每当尝试将其转换为字符串时都应使用该新函数。 任何想法为什么这不起作用?
根据规范( console.log- > Logger- > Printer ), console.log
的实现最终取决于实现。
因此,很可能在环境中您正在执行console.log(obj)
,而不仅仅是Printer("log", obj.toString())
。
function Test() { this.myTest = "Test"; } Test.prototype.toString = function testToString() { return this.myTest; }; var test = new Test(); console.log(test.toString());
基于此处的一些答案,我能够使用以下代码解决此问题。 尽管它与某些现有答案相似,但还是有些许不同,因此决定在此处发布。
function Test() {
this.myTest = "Test";
}
Test.prototype.toString = function testToString() {
return this.myTest;
};
var test = new Test();
console.log(test + "");
因此,只需在console.log
的末尾添加+ ""
即可正常运行,并将运行toString
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.