我有一个类:
class Test{
contructor(){
this.x = "test"
}
}
var t = new Test()
var toString = Object.prototype.toString
console.log(toString.call(t))
日志打印[object Object]
,我希望它打印类似[object Test]
的内容,我该怎么做?我尝试做
Test.prototype.toString = function() {
return "[object Test]"
}
但这不起作用,有什么帮助吗?
最佳答案
您可以使用Symbol.toStringTag其推出是为了完全满足您的需求:
class Test{
contructor(){
this.x = "test";
}
get [Symbol.toStringTag]() {
// either return 'Test' or ...
return this.constructor.name;
}
}
var t = new Test;
var toString = Object.prototype.toString;
console.log(toString.call(t));
但是,如果您使用转译器(Babel、TypeScript)并且您的目标是 ES5 而不是 ES2015+ (ES6+),并且您的目标浏览器不支持 Symbol.toStringTag
,那么您运气不好,因为除非您覆盖 Object.prototype.toString
以考虑类,但您的更改不会在其他第三部分脚本之前生效,这些脚本可能会捕获原始 toString
> 因此它不起作用,没有办法以可靠的方式为与 Symbol.toStringTag
不兼容的引擎提供此类功能。
关于javascript - 如何更改Object.prototype.toString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59253195/