Javascript OOP - 继承,原型设计,回调函数

时间:2013-10-18 07:55:24

标签: javascript oop inheritance callback

我正在尝试在Javascript中使用OOP继承,原型设计和回调函数。请你看看我的JSfiddel http://jsfiddle.net/Charissima/5g6GV/。 第一个问题已在Javascript OOP - inheritance and prototyping中得到解决,但遗憾的是回调函数不再起作用。

        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;

1 个答案:

答案 0 :(得分: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.