简体   繁体   English

我可以在console.log中将对象打印为类似于日期的字符串吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM