在两个ES6父族子类中,是否可以在子类执行后立即在父类中执行某些代码



示例:

class Parent { constructor() {} }  
class Child { constructor() { super(); someChildCode(); } }   

我只想在SomechildCode((之后执行一些代码。是的,我可以将其放在那里,但是要求没有将该代码放在那里。

因为有太多(n(个子课,只有一个父母,所以我不想重复代码(n(次。

P.S。我希望在创建子对象时像new Child((一样简单的清洁代码解决方案。

P.S。下降器,想解释吗?我意识到这项任务可能无法解决,这就是为什么我问了这个问题,以确保是否是这种情况。

如果您确实需要在施工时在每个子类中运行完全相同的代码,则该常见代码可能属于父构建体。但是,也许您需要一些特定于儿童的代码才能在常见代码之前运行,在这种情况下,您仍然有问题。

无论哪种方式,一种可能的解决方案都不是根本不覆盖子类中的构造函数,而是让他们继承父构造器,其中包含任何常见的代码以及前和后挂钩,您可以在必要的儿童课。例如:

class Parent {
    // do not override the constructor, conceptually "final"        
    constructor() {
        this.beforeCommonConstructorCode();
        // add any common constructor code here
        console.log("Common constructor code")
        this.afterCommonConstructorCode();
    }
    // override this in child classes as needed
    public beforeCommonConstructorCode() {
        // empty
    }
    // override this in child classes as needed
    public afterCommonConstructorCode() {
        // empty
    }
}
new Parent();
// in console:
// >> Common constructor code

,当您子类Parent时,您将构造函数不单独放置,并将代码添加到适当的方法:

class Child extends Parent {
    // remember, do not override constructor
    public beforeCommonConstructorCode() {
        console.log("Child pre-constructor code")
    }
    public afterCommonConstructorCode() {
        console.log("Child post-constructor code")
    }
}
new Child();
// in console:
// >> Child pre-constructor code
// >> Common constructor code
// >> Child post-constructor code

请注意,打字稿不会阻止儿童类覆盖构造函数(没有" final"关键字或功能(,因此需要纪律。否则,我认为这是您喜欢的方式。您不必在每个子类中放置常见代码。

希望有帮助。祝你好运。

如果我正确理解这一点,则可以有一个中间父母来实现这一目标,鉴于您的代码是通用的,并且不依赖孩子。

class Parent(){
}
class InterMediateParent extends Parent{
   constructor(){
      super();
      someCode();
   }
}
class Child extends InterMediateParent{
    constructor(){
     super();
    }
}

您可以将该函数添加到 parent prototype ,以便在所有子对象中仅维护一个副本,并在Child的构造函数中调用该函数。

class Parent { 
  constructor() {
  
  } 
} 
Parent.prototype.someCommonCode = function() {
  console.log("Common code for all Parent as well as it's child objects");
}
class Child extends Parent {
  constructor() {
    //Child class code
    super();
    
    //Some child code
    this.someChildCode();
    
    //Call Parent's common function
    super.someCommonCode();
  }
  
  someChildCode() {
     console.log("Some child code");
  }
}
let child1 = new Child();
let child2 = new Child();

最新更新