简体   繁体   English

向上干燥-如果不存在实例,则调用类方法,否则调用实例方法

[英]DRY up - Call class method if no instance exists, otherwise call instance method

Situation 情况

If input is a "start", automatically calculate the "end" and then prefill the page with the "end" 如果输入是“开始”,则自动计算“结束”,然后用“结束”预填充页面

If input is a "end", simply prefill the page with it 如果输入是一个“结束”,只需用它预填充页面

I'm trying to write a class to handle this functionality. 我正在尝试编写一个类来处理此功能。

class EndVal(start_value) {
  constructor() {
    this.end_value = start_value + 10
    $("#end").text(this.end_value)
  }

  static prefill(end_value) {
    $("#end").text(end_value)
  }
}

Based on the above code if what you have is a "start", you'd just do new EndVal(start_value) , but if you already have an "end" rather than instantiating a new object, you can just do EndVal.prefill(end_value) . 根据上面的代码,如果您拥有的是“开始”,则只需执行new EndVal(start_value) ,但是如果您已经拥有“结束”而不是实例化新对象,则只需执行EndVal.prefill(end_value) But it isn't very DRY... I'm wondering how to fix it, and somehow link the instance and class methods? 但这不是很干...我想知道如何修复它,并以某种方式链接实例和类方法?

The prefill method should use the passed argument instead of this . prefill方法应使用传递的参数代替this Now you can all the method from the constructor: 现在,您可以从构造函数中获取所有方法:

 class EndVal { constructor(start_value) { this.end_value = start_value + 10 this.constructor.prefill(this.end_value); } static prefill(end_value) { console.log(end_value); } } const endVal = new EndVal(15); EndVal.prefill(28); 

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

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