There's a couple ways to define an "object" in JavaScript.
The following uses a standard function to declare a class and some attributes and an accessor:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.display = function() {
return '' + this.year + ' ' + this.make + ' ' + this.model;
}
}
car = new Car('2006', 'Hyundai', 'Elantra');
console.log('I drive a ' + car.display());
According to things I've read, and logic, this is actually slightly inefficient if you want to instantiate a whole fleet of cars. That's because the code declaring the accessor runs each and every time, which is both slowing you down (processing time) and bloating you up (taking up memory for each object with an anonymous function). The Better Way™ is to use prototype
:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Car.prototype.display = function() {
return '' + this.year + ' ' + this.make + ' ' + this.model;
}
car = new Car('2006', 'Hyundai', 'Elantra');
console.log('I drive a ' + car.display());
This is all well and good, except that I tend to prefer my methods to be all scoped inside of the "class" to which they belong. The question I have is, is this a common way to solve the prototyping problem, or is it frowned upon? It's not as inefficient as redeclaring the functions each time, but it's slightly less efficient than definitively declaring the functions only once:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
if (this.prototype.display) {
this.prototype.display = function() {
return '' + this.year + ' ' + this.make + ' ' + this.model;
}
}
}
car = new Car('2006', 'Hyundai', 'Elantra');
console.log('I drive a ' + car.display());
I'm actually not entirely sure if that'll work, as I'm unsure if this.prototype
inside the declaration refers to the same thing as Car.prototype
(I'd generally prefer to keep the class name written in as few places as possible) but I'm about to Try It And See.
Best I can seem to come up with: