【问题标题】:Call method from one class when calling methods from another从一个类调用方法时从另一个类调用方法
【发布时间】:2019-12-13 09:41:56
【问题描述】:

我有两个课程:首先检查文件是否存在并且有效;第二个用那个文件做一些东西:

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

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

我想要的是第一类的方法在第二类的每个方法中自动调用。 这有点棘手,但我真的不想手动做,像这样:

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

class Modificator {
   action1(){ 
      let status = Validator.check();
      ...
   }
   action2(){ 
      let status = Validator.check();
      ...
   }
}

【问题讨论】:

  • Validator和Modificator是什么关系?为什么所有的 Modificator 都需要从 Validator 调用同一个静态方法?

标签: javascript class


【解决方案1】:
  1. 使用包装器

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()

但是请注意,如果您要继承 Modificator,您可能会忘记重新包装您的方法...

  1. 通过签订合同

更常见的是通过签订合同并委托实施合同是否履行。

这样你在扩展时不必担心,因为检查是在基类中进行的。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2016-10-12
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多