[英]Can I print Object as string like Date in console.log?
When I create the new Date object and using console.log shows not object but time as string. 当我创建新的Date对象并使用console.log时,对象不是时间而是字符串。 However, MyObject is print as Object.
但是,MyObject打印为对象。
Example: 例:
const date = new Date();
console.log(date);
const MyObject = function() {
this.name = 'Stackoverflow',
this.desc = 'is Good'
};
console.log(new MyObject());
Result: 结果:
2017-04-06T06:28:03.393Z
MyObject { name: 'Stackoverflow', desc: 'is Good' }
But I want to print MyObject like below format without using function or method. 但是我想不使用函数或方法来打印如下格式的MyObject。
Stackoverflow is Good
In java, I can override toString ()
to implement this. 在java中,我可以重写
toString ()
来实现这一点。 Is it possible in javascript too? JavaScript也可能吗?
I don't think console.log
provides any mechanism to tell it what representation to use for the object. 我不认为
console.log
提供任何机制来告诉它要使用哪种表示形式的对象。
You can do console.log(String(new MyObject()));
你可以做
console.log(String(new MyObject()));
and give MyObject.prototype
a toString
method: 并给
MyObject.prototype
一个toString
方法:
const MyObject = function() {
this.name = 'Stackoverflow';
this.desc = 'is Good';
};
MyObject.prototype.toString = function() {
return this.name + this.desc;
};
As you're using ES2015+ features (I see that from const
), you might also consider class
syntax: 当您使用ES2015 +功能(我从
const
看到)时,您可能还会考虑class
语法:
class MyObject {
constructor() {
this.name = 'Stackoverflow';
this.desc = 'is Good';
}
toString() {
return this.name + this.desc;
}
}
tips: in javascript ,you still can use "override" a method to impletement it 提示:在javascript中,您仍然可以使用“替代”方法来实现它
demo: 演示:
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.