简体   繁体   English

从一个类调用方法时从另一个类调用方法

[英]Call method from one class when calling methods from another

I have two classes: first on checks that file exists and it's valid;我有两个类:首先检查文件是否存在且有效; second one make some stuff with that file:第二个使用该文件制作一些东西:

class Validator {
   constructor(){
      this.file = './file.json';
   }
   check(){ ... }
}

class Modificator {
   action1(){ ... }
   action2(){ ... }
}

What I want is the method from first class automatically calls inside each method from the second class.我想要的是第一类的方法在第二类的每个方法中自动调用。 It's a bit tricky stuff, but I'm really don't want to do it manually, like so:这有点棘手,但我真的不想手动完成,如下所示:

class Validator {
   constructor(){
      this.file = './file.json';
   }
   static check(){ ... }
}

class Modificator {
   action1(){ 
      let status = Validator.check();
      ...
   }
   action2(){ 
      let status = Validator.check();
      ...
   }
}
  1. By using a wrapper通过使用包装器

 class Validator { static check () {console.log('checked')} static checkCbk (fn) { return _ => { this.check() //then callback fn() } } } class Modificator { //via public instance field action1 = Validator.checkCbk(function () { console.log('mod::action1') }) } //or by prototype Modificator.prototype.action2 = Validator.checkCbk(function(){ console.log('mod::action2') }) var m = new Modificator() m.action1() m.action2()

However notice that if you were to subclass Modificator , you could forget to rewrap your methods...但是请注意,如果您要继承Modificator ,您可能会忘记重新包装您的方法......

  1. By making a contract通过签订合同

More commonly by making a contract and delegating to implem if contract is fulfilled.更常见的是通过订立合同并在合同履行后委托执行。

This way you don't have to worry when extending since check is made in base class anyway.这样您在扩展时就不必担心,因为无论如何检查都是在基类中进行的。

 class Validator { static check () {console.log('checked')} } class Contract { action1 () { Validator.check() this._action1() } } class M2 extends Contract { _action1 () { console.log('mod2::action1') } } var m = new M2() m.action1()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM