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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With