![](/img/trans.png)
[英]How to print the object like string in console.log in Javascript?
[英]Can I print Object as string like Date in console.log?
当我创建新的Date对象并使用console.log时,对象不是时间而是字符串。 但是,MyObject打印为对象。
例:
const date = new Date();
console.log(date);
const MyObject = function() {
this.name = 'Stackoverflow',
this.desc = 'is Good'
};
console.log(new MyObject());
结果:
2017-04-06T06:28:03.393Z
MyObject { name: 'Stackoverflow', desc: 'is Good' }
但是我想不使用函数或方法来打印如下格式的MyObject。
Stackoverflow is Good
在java中,我可以重写toString ()
来实现这一点。 JavaScript也可能吗?
我不认为console.log
提供任何机制来告诉它要使用哪种表示形式的对象。
你可以做console.log(String(new MyObject()));
并给MyObject.prototype
一个toString
方法:
const MyObject = function() {
this.name = 'Stackoverflow';
this.desc = 'is Good';
};
MyObject.prototype.toString = function() {
return this.name + this.desc;
};
当您使用ES2015 +功能(我从const
看到)时,您可能还会考虑class
语法:
class MyObject {
constructor() {
this.name = 'Stackoverflow';
this.desc = 'is Good';
}
toString() {
return this.name + this.desc;
}
}
提示:在javascript中,您仍然可以使用“替代”方法来实现它
演示:
let myobj={id:1,name:'hello'};
Object.prototype.toString=function(){
return this.id+' and '+this.name
}; //override toString of 'Global' Object.
console.log(obj.toString());// print: 1 is hello
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.