I'm trying to use OOP in Javascript with inheritance and prototyping. Would you please have a look at my JSfiddel http://jsfiddle.net/Charissima/daaUK/. The last value is the problem, thank you. I cannot understand why the function drive with raceCar doesn't get the totalDistance, which a set per putTotalDistance.
function Car () {
var that = this;
this.totalDistance = 0;
this.putTotalDistance = function(distance) {
that.totalDistance = distance;
};
this.getTotalDistance = function() {
return this.totalDistance;
};
this.drive = function(distance) {
that.totalDistance += distance;
return that.totalDistance;
};
this.privateFunc = function() {
return 'car ' + this.totalDistance;
};
};
function RaceCar (initialDistance) {
var that = this;
this.prototype = new Car();
this.drive = function(distance) {
return that.prototype.drive(2*distance);
};
this.privateFunc = function() {
return 'raceCar ' + that.getTotalDistance();
};
};
RaceCar.prototype = new Car();
car = new Car;
raceCar = new RaceCar;
car.putTotalDistance(200);
alert('car totalDistance = ' + car.drive(10) + ' - ok');
raceCar.putTotalDistance(200);
alert('raceCar totalDistance before drive = ' + raceCar.getTotalDistance() + ' - ok');
alert('raceCar totalDistance after drive = ' + raceCar.drive(10) + ' Why not 220?');