Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inheritance using apply

I'm trying to extend class B to class A, and class A to class Super, using the function apply. The following code works OK:

function Super() {
    this.talk = function () {
        alert("Hello");
    };
}

function A() {
    // instance of A inherits Super
    Super.apply(this);
}

function B() {
    // instance of B inherits A
    A.apply(this);
}

var x = new B();
x.talk(); // Hello

But what if I want to class A inherits from class Super, not just its instances? I tried this:

function Super() {
    this.talk = function () {
        alert("Hello, I'm the class");
    };

    // function of the class' instance?
    this.prototype.talk = function () {
        alert("Hello, I'm the object");
    };
}

function A() {
    // nothing here
}

// A inherits from Super, not its instance
Super.apply(A);


function B() {
    // instance of B inherits A
    A.apply(this);
}

A.talk(); // static function works!

var x = new B();
x.talk(); // but this doesn't...

Am I doing something wrong?

like image 953
wm1sr Avatar asked May 12 '26 22:05

wm1sr


1 Answers

function Super() { }

// Static method, called by Super.talk()
Super.talk = function () {
    alert("Hello, I'm the class");
};

// Prototype method, should be called by instance
Super.prototype.talk = function () {
    alert("Hello, I'm the object");
};

function A() {
    // 'override' purposes
    Super.apply(this, arguments);
    // ..
}

// A inherits from Super
A.prototype = Object.create(Super.prototype);
A.prototype.constructor = A;

function B() { 
    A.apply(this, arguments);
}

// B inherits from A
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

// A.talk() won't work, of course.

var x = new B();
x.talk();
like image 82
Roy Miloh Avatar answered May 15 '26 13:05

Roy Miloh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!