我想在继承和原型的Javascript中使用OOP。请你看看我的JSFiddel http://jsfiddle.net/Charissima/daaUK/。最后一个值是问题,谢谢。 我不明白为什么使用raceCar的驱动器没有得到totalDistance,哪一个set putTotalDistance。Javascript OOP - 继承和原型
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?');
为什么? *如果它没有解释它,那么尝试这个*答案是非常不令人满意的。 – Bart
够公平的。我会添加一些东西。 – Todd