0

我正在尝试在具有继承、原型设计和回调函数的 Javascript 中使用 OOP。请你看看我的 JSfiddel http://jsfiddle.net/Charissima/5g6GV/。第一个问题已经在J​​avascript OOP 中解决了——继承和原型设计,但不幸的是回调函数不再起作用。

        function Car () {    
            this.totalDistance = 0;
        };

        Car.prototype.putTotalDistance = function(distance) {
            this.totalDistance = distance;
        };

        Car.prototype.getTotalDistance = function() {
            return this.totalDistance;      
        };  

        Car.prototype.drive = function(distance) {
            this.totalDistance += distance;     
            return this.totalDistance;
        };


        function RaceCar () {};
        RaceCar.prototype = new Car();
        RaceCar.prototype.parent = Car.prototype;
        RaceCar.prototype.drive = function(distance) {
            return this.parent.drive.call(this, (distance * 2));
        };                     

        var myText;
        car = new Car;
        raceCar = new RaceCar;          

        car.putTotalDistance(200);
        myText = 'car totalDistance = ' + car.drive(10) + ' - ok<br>';

        raceCar.putTotalDistance(200);
        myText += 'raceCar totalDistance before drive = ' + raceCar.getTotalDistance() + ' - ok<br>';
        myText += 'raceCar totalDistance after drive = ' + raceCar.drive(10) + ' - ok<br><br>';                                                     

        car.putTotalDistance(0);            
        raceCar.putTotalDistance(100);
        var drivingFunctions = [car.drive, raceCar.drive];

        myText += drivingFunctions[0](10) + '<br>';
        try {
            myText += drivingFunctions[1](100) + '<br>';        
        }
        catch(err) {
            myText += err + + '<br>'
        }

        document.body.innerHTML = myText;
4

1 回答 1

2

您已将这两个函数放在一个数组中,因此在调用时this会进行更改。您可以使用功能bind

   var drivingFunctions = [car.drive.bind(car), raceCar.drive.bind(raceCar)];

这里有一个例子可以帮助你理解:

function Man(name){
    this.name = name;
    this.getName = function(){
      return this.name;  
    };
}
var man = new Man('toto');
var a = [man.getName];
console.log(a[0]());//undefined
a.name = 'titi';
console.log(a[0]());//titi, because this refers to the array.
于 2013-10-18T08:12:45.877 回答