I want to make unique sets of cars that can be held by different people. Cars will have similar basic specifications, but some of their properties and methods will change.
The problem is that I cannot figure out how this should work. How do you handle or instantiate instances in JavaScript?
var Car = function(make, country) { this.make = make; this.country = country; }; var Ferrari = new Car('Ferrari', 'Italy'); var fred = new Person() {}; var fred.cars['Ferrari'] = new Ferrari(1200, 300000);
This causes this error for obvious reasons. I know this is not a constructor (see below).
Uncaught TypeError: Ferrari is not a constructor
What I'm looking for is something like this. Each individual Ferrari will have a different price and a higher price.
var Ferrari = function(currentPrice, miles) } this.currentPrice = currentPrice; this.miles = miles; // this is an instance of car, aka it needs the result of this: // new Car('Ferrari', 'Italy'); };
Fred Ferrari is an example of a Ferrari, which is an example of a car. The problem is that I can't think of a way to make a constructor a constructor. Is there a way to do this, or am I just doing it wrong?
Other notes:
I know that I could just make each type of car a static JSON-like object, and then make instances of this and add new unique values. However, I would like to be able to keep the car as a designer, so I can easily do more when I need to.
I clearly lack an understanding of OOP or JavaScript here, but it would be great if someone could point me in the right direction.
javascript constructor oop instances
jamcd
source share