2017-04-06 11 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 
相關問題