[英]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.