我找不到解决此问题的方法。我整天都在撞墙。
假设我们具有以下类层次结构:
class A {
async name() { ... }
}
class B extends A {
async age() { ... }
}
class C extends A {
async group() { ... }
}
class D extends B {
constructor() {
super(...)
this.C = new C(...);
}
async group() { return await this.C.group(); }
}
因为JavaScript不支持多重继承,所以我遇到了一个问题。我想以一种可以调用函数group()
的方式来组合对象的原型,而无需编写上面的重复代码。绝对必须能够直接在类外部的对象D上调用group()
,即使它是class C
的实例。
我如何结合他们的原型?我已经尝试过
class A {
appendPrototype(obj) {
if (obj instanceof A)
for (let k in obj.__proto__) {
this.__proto__[k] = obj.__proto__[k];
}
}
}
.
.
. // Same two classes, B and C
class D extends B {
constructor(...) {
super(...);
const c = new C(...);
this.appendPrototype(c);
}
}
我无法调用函数group()
的实例class D
。这是为什么?在不编写第一个示例中的重复代码的情况下,如何实现?
答案 0 :(得分:0)
您可以做的是将其分配给类D的原型,即类C的方法。
这样,D的所有实例将具有 FrameBuffer fbo = new FrameBuffer(Pixmap.Format.RGBA4444, screenWidth, screenHeight, true);
ModelBatch batch = new ModelBatch();
fbo.begin(); // make fbo the current buffer
Gdx.gl.glViewport(0, 0,screenWidth, screenHeight);
Gdx.gl.glClear(GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
batch.begin(camera);
batch.render(instance, environment);
batch.end();
try{
FileHandle fh = new FileHandle(output);
Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0,0,screenWidth,screenHeight);
PixmapIO.writePNG(fh, pixmap);
pixmap.dispose();
}catch (Exception e){
e.printStackTrace();
}
fbo.end(); // Now you can draw on the display again
batch.dispose();
fbo.dispose();
方法,该方法与类C中定义的方法相同,并且您可以对所有其他子类执行相同的操作。
group
无论如何,就您而言,我会进行合成(就像您在D中对C所做的那样),然后调用以下方法:
class A {
async name() {
console.log('A - name');
}
}
class B extends A {
async age() {
console.log('B - age');
}
}
class C extends A {
async group() {
console.log('C - group');
}
}
class D extends B {
constructor() {
super();
}
}
D.prototype.group = C.prototype.group;
const d = new D();
d.group();
,您可以避免使用d.c.group()
逻辑。