dimanche 10 mai 2015

Javascript Inheritance Overriding

There's a lot of confusing literature on the net about Javascript overriding. But, I haven't found one any that does what I need. I'm trying to enable inheritance and method override, but in a particular way.

Imagine:

var A = function(amount) {
    this.amount = amount;
    var _this = this;

    this.method1 = function() {
        some_asynchronous_function(this.amount, function(result) {
            _this.method2(result);
        });
    };
    //The function we want to override!
    this.method2 = function(result) {
        do_stuff(result);
    };
};

var B = function(amount) {
    this.method2 = function(result) {
        do_different_stuff(result);
    };
    A.call(this, amount);
};
B.prototype = Object.create(A.prototype);

My goal is to be able to keep everything from the A class except for the the this.method2. However, when I instantiate B in my code and call B.method1, it executes the method2 from A. Is there a way to mix and match what I keep in with Javascript?

Aucun commentaire:

Enregistrer un commentaire