Reputation: 503
I have some JS code here:
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);
So I want some interesting output in the console:
console.log('Car: ' + bmw); // Car: BMW X5 2010
How to do it without calling any methods?
THANKS!
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;
};
}
Upvotes: 3
Views: 73
Reputation: 382092
You may override the toString
method :
Car.prototype.toString = function() {
return this.model + ' ' + this.year;
};
This method is automatically called when a string representation of the object is needed (for example when you do "somestring" + yourObject
.
Reference : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/toString
Upvotes: 0
Reputation: 21899
console.log
just outputs to the console what it is given as a parameter. In your case, you are giving it a string (by concatenating a string with an object).
If you were to simply put console.log(bmw)
you would see an interesting outcome - depending on which web inspector you are using, you will be able to click through all of bmw
's properties... very nice.
The representation of console.log(bmw)
in Chrome Developer Tools:
To answer your precise question, you can change the string representation of an object by overriding its toString()
function.
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
Upvotes: 1
Reputation: 262919
You can override your object's toString() method:
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;
};
}
You can test the results in this fiddle.
Upvotes: 0