2012-08-23 69 views
3

我有一些JS代碼在這裏:對象必須返回功能

function Car(manufacturer, model, year) { 
    this.manufacturer = manufacturer; 
    this.model = model; 
    this.year = year == undefined ? new Date().getFullYear() : year; 
    this.getInfo = function(){ 
     return this.manufacturer +' '+ this.model +' '+ this.year; 
    }; 
} 

var bmw = new Car("BMW", "X5", 2010); 

所以我想在控制檯中一些有趣的輸出:

console.log('Car: ' + bmw); // Car: BMW X5 2010 

如何做到這一點,而無需調用任何方法?

謝謝!

I need the 'getInfo' method, so I have simply changed my code: 
function Car(manufacturer, model, year) { 
    this.manufacturer = manufacturer; 
    this.model = model; 
    this.year = year == undefined ? new Date().getFullYear() : year; 
    this.toString = this.getInfo = function(){ 
     return this.manufacturer +' '+ this.model +' '+ this.year; 
    }; 
} 

回答

0

您可以覆蓋您的對象的toString()我thod:

function Car(manufacturer, model, year) { 
    this.manufacturer = manufacturer; 
    this.model = model; 
    this.year = year == undefined ? new Date().getFullYear() : year; 
    this.toString = function() { 
     return this.manufacturer + ' ' + this.model + ' ' + this.year; 
    }; 
} 

您可以在this fiddle中測試結果。

+0

因此,據我所知,'toString'方法被稱爲每次我調用一個對象? –

+2

否:僅當需要字符串表示時。 ''somestring「+ aobject'就是這種發生的一個例子。 –

+0

感謝一個looot! –

1

console.log只是輸出到控制檯什麼它作爲參數給出。在你的情況下,你給它一個字符串(通過串聯一個對象的字符串)。

如果你只是簡單地把console.log(bmw),你會看到一個有趣的結果 - 取決於你使用的網絡檢查員,你將能夠點擊所有bmw的屬性...非常好。

在Chrome開發者工具的的console.log(bmw)表示:

enter image description here

要回答你確切的問題,你可以通過重寫其toString()功能改變對象的字符串表示。

function Car(manufacturer, model, year) { 
    this.manufacturer = manufacturer; 
    this.model = model; 
    this.year = year == undefined ? new Date().getFullYear() : year; 
    this.getInfo = function(){ 
     return this.manufacturer +' '+ this.model +' '+ this.year; 
    }; 

    // Build the string up as you wish it to be represented. 
    this.toString = function() { 
     var str = this.manufacturer + " " + this.model + " " + this.year; 
     return str; 
    }; 
} 

var bmw = new Car("BMW", "X5", 2010); 
console.log('Car: ' + bmw); // Car: BMW X5 2010 
相關問題