So how to use abstract factory method in JavaScript? For example in Java:
public abstract class SuperClass {
abstract String bar();
public String foo() {
return bar();
}
}
public class SubClass extends SuperClass{
@Override
String bar() {
return "bar";
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new SubClass().foo());
}
}
It shows bar
and just fine. But when I tried this in JavaScript:
var SuperClass = function () {};
SuperClass.prototype.foo = function () {
return this.prototype.bar();
};
var SubClass = function () {};
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;
SubClass.prototype.bar = function () {
return "bar";
};
var myClass = new SubClass();
console.log(myClass.foo());
I get Uncaught TypeError: Cannot read property 'bar' of undefined
. I tracked the bug and turns out, when SuperClass.prototype.foo
is being executed, SubClass.prototype
is still undefined
.
So, what's the right way to do that? Thanks you!
Aucun commentaire:
Enregistrer un commentaire