I have this Car function:
var Car = function(vendor, model, year) {
return {
vendor: vendor,
model: model,
year: year,
name: (function() {
return vendor + " " + model + " " + year;
})()
};
};
var foo = Car("Toyota","Corola",2007);
alert(foo.name); //alerts "Toyota Corola 2007"
This works, but I want the name to be able to change according to the vendor, model, and year.
taxi.vendor = "Mitsubishi";
alert(taxi.vendor); //still alerts "Toyota Corola 2007"
How can I instead make it alert Mitsubishi Corola 2007 according to the change of the vendor property?
EDIT: And the catch — name must remain a property that does not need to be called as a function.
With recent versions of WebKit (Safari, Chrome) or Firefox, you can define getter and setter functions:
Then you would do this:
And get the result that you want.
I don’t know if IE or Opera support this or which versions. If you need to support anything other than recent Safari, Chrome, or Firefox browsers then you’re better off using a function to access the name instead of leaving it as a property:
And then: