javascript - 使用 "pseudoclassical"模式在 JavaScript 中实现成员变量继承

标签 javascript oop inheritance

中,Douglas 介绍了所谓的“伪经典”模式作为实现继承的方式之一。不过,他给出的例子似乎无法实现成员变量的继承,因为原型(prototype)继承在构造“子类”时不会创建“父类(super class)”变量的副本。

举一个具体的例子,让我们考虑两个类:一个 InputStream 类,它处理底层输入机制,并提供一个简单的 read 接口(interface)来逐字节读取;以及一个继承InputStream并提供readUtf8接口(interface)来读取有效UTF8字符的Utf8InputStream类。那么在“伪经典”模式下这似乎是有问题的,因为所有 Utf8InputStream 将共享相同的底层 InputStream,并且事情显然会中断。

在我看来,使用组合而不是继承会很容易解决问题,但出于好奇,这里有没有办法实现成员变量的继承?

最佳答案

It then seems problematic under the "pseudoclassical" pattern as all the Utf8InputStream will share the same underlying InputStream and things will obviously break.

不,只有当你做错了并且 create an instance for the prototype 时才会发生这种情况。 。 Correct :

function Utf8InputStream(…) {
    InputStream.call(this, …);
    …
}
Utf8InputStream.prototype = Object.create(InputStream.prototype);

关于javascript - 使用 "pseudoclassical"模式在 JavaScript 中实现成员变量继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700897/

相关文章:

c# - 确定一个类是否实现了一个非常具体的接口(interface)

javascript - 如何获得数学函数的真实值

oop - 在 MATLAB 中覆盖父类(super class)方法和访问修饰符

javascript - Angular 2检查下一条路线OnDestroy

Java OO 设计 : a Person can be either Singer, 钢琴家或两者

oop - API — CFC与cfinclude

c++ - 尝试调用默认构造函数时没有匹配的构造函数

c# - 扩展方法是否类似于在 c# 中具有 "new"关键字方法?

javascript - "[Variable] was used before it was defined"错误

javascript - 在 ECMAScript 上使用 JSDoc 和扩展语法