3
更新:コードを回答から更新しました。 @Azamantesに感謝動的に作成された子コンストラクタ関数から親コンストラクタへの呼び出し
私は親のオブジェクト/コンストラクタを呼び出してみます。
HTMLコード:
<div style="width:50px; height: 50px; display: inline-block; background-color:red;" id="id0">BoxId0</div>
<div style="width:50px; height: 50px; display: inline-block; background-color:red;" id="id1">BoxId1</div>
<div style="width:50px; height: 50px; display: inline-block; background-color:red;" id="id2">BoxId2</div>
<div style="width:50px; height: 50px; display: inline-block; background-color:red;" id="id3">BoxId3</div>
Javascriptのコード:
function Child(parent, childID) {
var thisReference = this;
var parentReference = parent;
$(childID).on("click", function() {
parentReference.childCallMe(childID); // Gave on click 'TypeError: parentReference.childCallMe is not a function'
});
return {
getParent() { return parentReference },
getThis() { return thisReference },
getChild() { return childID },
}
}
function Mother(childrenCount) {
var thisReference = this;
var children = [];
var testText = "test";
// Will not work:
function childCallMe(id) {
alert("mohter: " + id);
}
// This will work:
this.childCallMe = function(id){ alert('mother' + id) };
for(var i = 0; i < childrenCount; i++) {
children[i] = new Child(thisReference, '#id' + i);
}
return {
getTestText() { return testText },
getThis() { return thisReference },
getChildren() { return children },
};
};
/*
Mother.prototype.childCallMe = function(id) {
alert(id);
//I need to call a function in Mother
};
*/
var mother1 = new Mother(4);
私は別のHTML要素のための「母親回以上再利用します。 「子ども」の数も変化する可能性があります。私は、この文脈をどのように使うべきか明確ではないと思う。 PHPではとても簡単です。 :(
私は「= {childCallMeするvar API:childCallMe、」に変更。、変更なし、同じエラー私はクリックイベント「警戒して子供に使用している場合(objParent .toSource()); '空のObject:'({}) 'が返されます。 –
これで動作します。 'Mother.prototype.chil下にdCallMeメソッドがあります。それは動作しませんでした。なぜなら、Motherオブジェクトを作成する方法では、関数への参照を保持することができないからです(Childオブジェクトを作成した後に関数を返すので、別の方法で行うこともできます。 – Azamantes
ありがとう!厄介なプロトタイプ:) –