如何更改Object.prototype.toString?
How to change Object.prototype.toString?
我有一个 class:
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]"
}
但这没有用,有什么帮助吗?
你可以这样做:
class Test {
contructor() {
this.x = "test"
}
toString() {
return "[object " + this.constructor.name + "]";
}
}
var t = new Test();
console.log(t.toString());
您可以使用 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
以考虑 类,但您的更改未被授予在其他第 3 部分脚本之前登陆,这些脚本可能会捕获一次原始 toString
,因此它不会工作,无法以可靠的方式为不兼容 Symbol.toStringTag
.
的引擎提供此类功能
我有一个 class:
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]"
}
但这没有用,有什么帮助吗?
你可以这样做:
class Test {
contructor() {
this.x = "test"
}
toString() {
return "[object " + this.constructor.name + "]";
}
}
var t = new Test();
console.log(t.toString());
您可以使用 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
以考虑 类,但您的更改未被授予在其他第 3 部分脚本之前登陆,这些脚本可能会捕获一次原始 toString
,因此它不会工作,无法以可靠的方式为不兼容 Symbol.toStringTag
.