まず、JS でのサブクラス化は通常、悪い考えです。なぜなら、すべてのインスタンスがプロパティとメソッドの独自のコピーを持っている拡張機能を取得していると人々が考えているからです...
...本当に、彼らはpublic static
親のものにアクセスしています。
さらに良いことに、そのようなpublic static
ものはカプセル化された変数にアクセスできないため、(パブリック インターフェイスを使用して) プライベート関数を使用してパブリックな静的データにデータを渡したり、そこから戻り値を収集したりしない限り、実際にはプライベート データを操作することはありません。
var Parent = function () {
this.static_prop = 0;
this.static_method = function (num) { this.static_prop += 1; return num + this.static_prop; };
};
var Child = function (num) {
this.public_func = function () { num = this.static_method(num); };
};
Child.prototype = new Parent();
var child = new Child(13);
child.public_func();
this.static_method
へのアクセスが0になるため、呼び出すだけでは役に立ちませんnum
。つまり、継承したものをラップして、プライベートデータを入力として使用するためのアクセスを許可することになります。つまり、ほとんどの書き込みを行うことになります。あなたの期待.prototype
は逆 だったので、継承に関係なく、とにかくやっているでしょう。
代わりに、依存性注入をお勧めしますか?
コンポーネントベースのプログラム?
var Iterator = function () {
var count = 0,
min = 0,
max = 0,
reset = function () { count = min; },
next = function () { count = count >= max ? min : count; return count += 1; },
set_min = function (val) { min = val; },
set_max = function (val) { max = val; },
public_interface = { reset : reset, count : count, set_min : set_min, set_max : set_max };
return public_interface;
},
Thing = function (iter) {
var arr = [],
currentObj = null,
nextObj = function () {
currentObj = arr[iter.next()];
},
add = function (obj) {
arr.push(obj); iter.set_max(arr.length);
},
public_interface = { next : nextObj, add : add };
return public_interface;
};
var thing = Thing(Iterator());
thing.add({});
thing.next();
これは複雑な例ですが、すべてのインスタンスには、ジョブを実行するために必要なものが正確に与えられます (コンストラクターが必要とするため、または、パブリック メソッドを介して、またはパブリック プロパティとして、後で依存関係を追加できます)。 .
各モジュールのインターフェイスは、プライベート データを取得するために予期しない静的ヘルパーをラップする必要がないため、必要に応じてシンプルかつクリーンにすることもできます...
これで、何がプライベートで、何がパブリックに拡張されているかがわかり、それらを配置したい場所にクリーンなインとアウトがあります。