简体   繁体   中英

Javascript OOP - inheritance, prototyping, callback function

I'm trying to use OOP in Javascript with inheritance, prototyping and callback functions. Would you please have a look at my JSfiddel http://jsfiddle.net/Charissima/5g6GV/ . The first problem is solved already in Javascript OOP - inheritance and prototyping , but unfortunately the callback functions don't work any more.

        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;

You've put the two functions in an array, so when called, this get changed. You could use function bind :

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

Here is an example to help you understand:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM