[英]Call parent class method (with this context) in child class
我使用了 JS 框架,其中與子組件的交互調用父組件上的操作。 我正在嘗試在普通 JS 中做類似的事情,但真的不知道怎么做。 我正在嘗試將父級綁定到傳遞給子級的操作。 但不能讓它工作。
我應該只使用事件嗎? 為什么在這種方法上使用事件?
這是我正在嘗試做的基礎知識:
class Parent {
constructor(){
for (let id=0; id<100; id++){
this.children.push(new Child(id, this.updateParent.bind(this)))
}
}
property = "Parent Property";
children;
updateParent(childId){
// Update parent using child Id
// I want to use this.property or other this.methods
}
}
class Child {
constructor(id, updateParent){
// Create HTML element
// Register event for element interaction
// Upon interaction --
updateParent(id)
}
}
const parent = new Parent()
謝謝!
你所擁有的似乎幾乎可以工作,這里有一些調整和日志記錄。
回調方法是一種合法的事件處理方式,請嘗試兩者並使用更適合您系統中所需的交互類型的方法。
class Parent { constructor() { this.children = [] for (let id = 0; id < 10; id++) { this.children.push(new Child(id, this.updateParent.bind(this))) } } childCount = 0 updateParent(childId) { console.log(`Child ${childId} updating Parent. youngest=${this.youngestChild}, count=${this.childCount}`) this.youngestChild = childId; this.childCount += 1; } } class Child { constructor(id, updateParent) { console.log("Child Born:", id) this.id = id updateParent(id) } } const parent = new Parent() console.log(parent.children)
你必須先定義孩子。
看看這個:
class Parent {
constructor(){
this.children = [];
for (let id=0; id<100; id++){
this.children.push(new Child(id, this.updateParent.bind(this)))
}
}
property = "Parent Property";
children;
updateParent(childId){
// Update parent using child Id
// I want to use this.property or other this.methods
console.log("Parent updated from Child ID: "+childId);
}
}
class Child {
constructor(id, updateParent){
// Create HTML element
// Register event for element interaction
// Upon interaction --
updateParent(id)
}
}
const parent = new Parent()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.