首页 > 解决方案 > 在子类中调用父类方法(使用此上下文)

问题描述

我使用了 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()

谢谢!

标签: javascript

解决方案


你所拥有的似乎几乎可以工作,这里有一些调整和日志记录。

回调方法是一种合法的事件处理方式,请尝试两者并使用更适合您系统中所需的交互类型的方法。

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)


推荐阅读