I’m stuck. In working on a section in codecademy’s JavaScript class relating to methods and objects that inherit these methods, I’ve become a bit confused. The problem that I’m on involves an original Object that is a Car that contains the method ‘accelerate.’ – I’m OK with this:
Objects are things within a class, i.e. they are all contain similar property. In this example our Objects are Cars. There can be many different kinds of cars, each with different property such as (different colors, makes, speed, etc). But they are all in the same ‘class’ (i.e. same kind of thing: cars)
Methods are Functions that manipulate Objects. In this example, if we have made a Car Object that has the property Blue and Ford and 10 mph, we can now do something with this object using a method. The codecademy project has us write an ‘accelerate’ Method that adds 10 to the speed. OK – so every time we send our car object to that method, it looks for the speed property and increases it by 10.
Inheritance is a way of making subsets of an Object so that they automatically get the properties that the ‘parent’ Object has, but can also be given new properties that the ‘parent’ Object does not have. In the present codecademy example, we are making an ElectricCar Object that inherits from the Car Object. No problem, this is a good example because we can easily see that it is still a kind of car and that means it makes sense that it should have all the same properties as other cars (color, make, speed – perhaps Blue, Chevy Volt, 20Mph) But we also want to give it properties that other cars do not have, like ‘electricity’ (meaning battery charge).
OK, here’s what I have with some notes to follow along an to indicate where I am having problems. Help is greatly appreciated.
function Car( listedPrice ) {
var price = listedPrice;
this.speed = 0;
this.numWheels = 4;
this.getPrice = function() {
return price;
};
}
Car.prototype.accelerate = function() {
this.speed += 10;
};
function ElectricCar( listedPrice ) {
var price = listedPrice;
this.electricity = 100;
}
ElectricCar.prototype = new Car();
// Write the accelerate method for ElectricCar here
myElectricCar.accelerate = function() {
this.speed += 20;
};
// Write the decelerate method for ElectricCar here
myElectricCar.decelerate = function(secondsStepped) {
this.speed -= (5*secondsStepped);
};
myElectricCar = new ElectricCar(500);
myElectricCar.accelerate();
console.log(“myElectricCar has speed ” + myElectricCar.speed);
myElectricCar.decelerate(3);
console.log(“myElectricCar has speed ” + myElectricCar.speed);