代码之家  ›  专栏  ›  技术社区  ›  Poul K. Sørensen

Typescript构造函数的默认值

  •  0
  • Poul K. Sørensen  · 技术社区  · 11 年前
    constructor(
          public templateHeaderRow = 'DefaultTableHeaderTemplate',
          public templateBodyRow = 'DefaultTableRowTemplate',
          private templateBase = _templateBase) {
    
              require([this.templateBase + templateHeaderRow + '.html', this.templateBase+ templateBodyRow + '.html'], () => console.log('fdsfdsdfsf'));
    }
    

    然后我这样称呼它: log = new ListViewBase(undefined,'LoggingTableRowTemplate');

    看起来有点愚蠢 (undefined,' 。有人能提出不同的设计方案吗?

    什么会很好,会是像C#中我可以做的事情 (parametername:value, another:value2) ,并且顺序对于可选参数来说并不重要。不过在打字稿中还没有发现类似的东西。

    使现代化

    替代方案我正在这样做:

    public templateHeaderRow = 'DefaultTableHeaderTemplate';
    public templateBodyRow = 'DefaultTableRowTemplate';
    private templateBase = _templateBase;
    
    constructor(configuration? : ListViewBaseConfiguration) {
        if (typeof configuration !== "undefined") {
            if (typeof configuration.templateBase !== "undefined")
                this.templateBase = configuration.templateBase;
            if (typeof configuration.templateBodyRow !== "undefined")
                this.templateBodyRow = configuration.templateBodyRow;
            if (typeof configuration.templateHeaderRow !== "undefined")
                this.templateHeaderRow = configuration.templateHeaderRow;
        }
    
    
        require(['template!' + this.templateBase + this.templateHeaderRow + '.html',
            'template!' + this.templateBase + this.templateBodyRow + '.html']);
    }
    

    但我必须写更多的代码来获得一些参数可以设置而另一些参数不能设置的行为。

    1 回复  |  直到 4 年前
        1
  •  2
  •   Fenton    11 年前

    我真的无法补充你在这里已经知道的内容。

    如果你在参数上使用默认值,你最好的办法是按可能性排序,即最有可能通过的先通过。

    如果您首先获得默认值,那么传递对象可能会稍微不那么麻烦,例如:

    var config = MyClass.GetConfig(); // static method call
    config.templateBodyRow = 'Not Default';
    

    然后,您可以合理地期望将对象中的所有值传递给构造函数。

    另一个选项可能是JavaScript的null联合:

    this.templateBodyRow = config.templateBodyRow || 'DefaultBodyRowTemplate';
    

    它只是比你的版本短。

    这只是一个选择——在没有命名参数的情况下,你是在一堆不充分的参数中选择最好的!