【发布时间】:2019-01-30 10:15:14
【问题描述】:
我有这个层次结构:
public abstract class Foo {};
public class A extends Foo {};
public class B extends Foo {};
我想在 javascript 中为这个层次结构建模。所以我尝试了这样的事情:
var Foo = function () {
this.doSomething = function(input) {
//do something
}
};
var A = function() {
Foo.call(this);
this.AdoSomething = function(input) {
this.doSomething();
//do more things
}
}
var B = function() {
Foo.call(this);
this.BdoSomething = function(input) {
this.doSomething();
//do more things
}
}
我这样设置层次结构:
var tempFoo;
if (type === 'A') {
A.prototype = Object.create(Foo.prototype);
tempFoo = new A();
tempFoo.AdoSomething(data);
} else {
B.prototype = Object.create(Foo.prototype);
tempFoo = new B();
tempFoo.BdoSomething(data);
}
这很好用。但我想知道是否有更好的方法来做到这一点。我希望 javascript 对象看起来像这样:
var Foo = function () {
this.doSomething = function(input) {
//do something
}
};
var A = function() {
Foo.call(this);
this.doSomething = function(input) {
//call Foo's doSomething, super.doSomething()
//do more things
}
}
var B = function() {
Foo.call(this);
this.doSomething = function(input) {
//call Foo's doSomething, super.doSomething()
//do more things
}
}
但我不能使用 super 或 class,因为 IE 不支持它。我使用this answer 尝试调用父方法(Foo 的 dosomething),如下所示:
Foo.prototype.doSomething.call(this)
但这没有用。我收到一条错误消息,提示无法读取未定义的属性调用。
在 javascript 中设置层次结构的最佳方法是什么?
【问题讨论】:
-
您将函数分配给
this.doSomething,而不是this.prototype.doSomething。
标签: javascript oop object inheritance polymorphism