更新:我更新了答案中的代码,现在可以使用了。感谢@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 元素,我会多次重复使用“母亲”。 “ child ”的数量也可以改变。我想我不清楚如何使用 this-context。在 PHP 中它非常简单。 :(
最佳答案
function Child(parent, childID) {
var thisReference = this;
$(childID).on("click", function() {
parent.childCallMe(childID); // Gives 'TypeError: parent.childCallMe is not a function'
});
return {
getThis() { return thisReference },
getChild() { return childID },
}
}
function Mother(childrenCount) {
var thisReference = this;
var children = [];
function childCallMe(id) {
alert(id);
}
for(var i = 0; i < childrenCount; i++) {
children[i] = new Child(this, '#id' + i);
}
return {
getThis() { return thisReference },
getChildren() { return children },
};
};
Mother.prototype.childCallMe = function(id) {
alert(id);
};
var mother1 = new Mother(4);
因此,在稍微改进您的代码后,我注意到您没有添加 Mother“类”中的 childCallMe
方法,因此 Child 没有看到它,因此出现了错误。
这是最有意义的方式:
function Child(parent, childID) {
this.id = childID;
$(childID).on("click", function() {
parent.childCallMe(childID); // Gives 'TypeError: parent.childCallMe is not a function'
});
}
function Mother(childrenCount) {
this.children = [];
function childCallMe(id) {
alert(id);
}
for(var i = 0; i < childrenCount; i++) {
this.children[i] = new Child(this, '#id' + i);
}
};
Mother.prototype.childCallMe = function(id) {
alert(id);
};
var mother1 = new Mother(4);
关于javascript - 从动态创建的子构造函数调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37522891/