我有一些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;
};
}
因此,據我所知,'toString'方法被稱爲每次我調用一個對象? –
否:僅當需要字符串表示時。 ''somestring「+ aobject'就是這種發生的一個例子。 –
感謝一個looot! –