如何在JavaScript注入对象中获取父类实例引用?
外部创建Child实例时传递Parent引用的解决方案
当Child对象在Parent类外部创建,且需要让Child持有Parent实例引用以调用其方法时,有几种简洁的实现方式,以下是最常用的两种:
方案一:给Child添加setter方法
通过在Child类中定义专门的方法接收Parent实例,Parent构造函数在拿到传入的Child对象后,主动调用该方法完成引用传递。这种方式既保持类的封装性,又逻辑清晰。
修正后的Child类:
class Child { private parent: Parent; constructor() {} // 定义setter方法接收Parent实例 public setParent(parentInstance: Parent): void { this.parent = parentInstance; } log() { // 增加判断避免未初始化时调用报错 if (this.parent) { this.parent.log("This is a log message from the child"); } } }
Parent类调整:
class Parent { private child: Child; constructor(child: Child) { this.child = child; // 将自身实例传递给Child this.child.setParent(this); } public log(message: string) { console.log(`Parent logged: ${message}`); } }
使用示例:
// 外部创建Child实例 const child = new Child(); // 创建Parent时传入Child,自动完成引用传递 const parent = new Parent(child); // 调用Child的log方法,会触发Parent的log child.log();
方案二:给Child构造函数添加可选Parent参数
给Child的构造函数添加一个可选的Parent参数,外部创建Child时可暂时不传,后续通过setter补充引用。这种方式灵活性更高,适合需要延迟绑定的场景。
代码示例:
class Child { private parent?: Parent; constructor(parentInstance?: Parent) { this.parent = parentInstance; } public setParent(parentInstance: Parent): void { this.parent = parentInstance; } log() { // 使用可选链操作符,避免未初始化时抛出错误 this.parent?.log("This is a log message from the child"); } }
Parent类的使用和方案一一致,外部创建Child时无需提前知道Parent实例,等Parent创建后再完成绑定即可。
内容的提问来源于stack exchange,提问作者Kris
相关产品推荐
相关产品推荐

