複数のインスタンスのプロパティ/メソッドを共有する方法を理解するのにいくつかの困難があります。JavaScript - 複数のインスタンス間でプロパティを継承する
インスタンスの新しいオブジェクトObject.create()
を作成してプロパティを継承することは可能です。しかし、それは複数の(子)インスタンス間で共有できない新しいオブジェクトを作成します。
私の目的は、プロパティとヘルパーメソッドを保持するParent関数を作成することです。また、このプロパティ/メソッドは、子関数間で共有する必要があります。子(または親)メソッドがプロパティを変更する場合、それはアクセス可能であり、すべてのインスタンス(親/子)に反映される必要があります。
どのようにこのような動作を実現できますか?ここで
(ない私が欲しいものである)古典の継承の例が、私は達成したいの原則を示しています
// File 1 - Parent
var Parent = function() {
this.var1 = 'var1';
this.var2 = 'var2';
};
Parent.prototype.setVar = function(name, arg) {
this[name] = arg
};
Parent.prototype.getVar = function(name) {
return this[name];
};
// File 2 - Child 1
var Child1 = function() {
Parent.call(this);
};
Child1.prototype = Object.create(Parent.prototype);
Child1.prototype.constructor = Child1;
Child1.prototype.print = function() {
this.setVar('var1', 'test var 1');
this.setVar('var2', 'test var 2');
console.log(this.var1, this.var2)
};
// File 3 - Child 2
var Child2 = function() {
Parent.call(this);
};
Child2.prototype = Object.create(Parent.prototype);
Child2.prototype.constructor = Child2;
Child2.prototype.print = function() {
console.log(this.var1, this.var2)
};
var Child1 = new Child1();
var Child2 = new Child2();
Child1.print(); // test var 1 test var 2
Child2.print(); // var1 var2
/*** => How to share/inherit the variables from Parent in all children (Child1, Child2, etc...)
Child1.print(); // test var 1 test var 2
Child2.print(); // test var 1 test var 2
***/
フィドル:https://jsfiddle.net/guL2ahpq/たぶん
私は非常に遠くコンセプトのよを探しています。 誰かが簡単に私が探しているものを達成する方法を説明できることを願っています。また、あなたは上でこれらの変数を設定することができJS https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
JSは '共有プロパティ'(プロトタイプチェーンから)を読み取ることができますが、書き込み時には常にローカルプロパティを作成します。 – Dormilich
はい、わかっています。しかし、どこの場所でも更新できる同じプロパティをすべてのインスタンスにわたって共有するためにコードを実装する方法はありますか? OOPでこれを達成する方法はありますか? – freaky
共有プロパティを更新することはできません。それがJSの仕組みです。 – Dormilich