gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:25:47 26 4
gpt4 key购买 nike

中,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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com