2017-04-06 123 views
0

当我创建新的Date对象,并使用console.log显示不是对象,但时间作为字符串。 但是,MyObject打印为对象。我可以在console.log中将Date对象打印为字符串吗?

实施例:

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?

+0

@ T.J.Crowder你为什么删除你的答案? –

+0

@RajaprabhuAravindasamy:因为'console.log'不使用'toString'。我现在纠正并取消删除它。 –

+1

@ T.J.Crowder哦,那是我的错字。谢谢:) –

回答

0

我不认为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; 
    } 
} 
0

提示:在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 
相关问题