代码之家  ›  专栏  ›  技术社区  ›  tacos_tacos_tacos

使用tcomb,我是遗漏了什么,还是无法定义实例函数?

  •  0
  • tacos_tacos_tacos  · 技术社区  · 10 年前

    我正在尝试使用 tcomb 现在失败了,因为我无法理解如何定义实例函数。

    假设我有一种类型:

    t.struct({
      year: t.Integer,
      monthIndex: t.Integer,
      dayIndex: t.maybe(t.Integer),
      indexInMonth: t.maybe(t.Integer),
      title: t.Str,
      subtitle: t.maybe(t.Str),
      description: t.maybe(t.Str),
      iconIdentifier: t.maybe(t.Str),
    })
    

    到现在为止,一直都还不错。

    这个问题

    现在假设我想添加一个 month 例子 可以读取的方法 this 并获得正确的月份名称:

    month() {
      return MonthsInYear[this.monthIndex]
    },
    

    如果我尝试将其添加到上面的内部,它就是看不到它。

    const b1 = CalEvent({
      year: 2015,
      monthIndex:2,
      title: 'abc',
      description: 'abc'
    })
    
    console.log(b1.month)
    

    mixin 或者其他什么 每次定义函数 .

    我最初有 of 语法和函数一样 compare

    t.struct({
      year: t.Integer,
      monthIndex: t.Integer,
      compare: t.func([CalEvent], CalEventComparisonResult).of(
        (toCompare) => CalEvent(compare(this,toCompare))
      ),
      dayIndex: t.maybe(t.Integer),
      indexInMonth: t.maybe(t.Integer),
      title: t.Str,
      subtitle: t.maybe(t.Str),
      description: t.maybe(t.Str),
      iconIdentifier: t.maybe(t.Str),
    })
    

    仍然没有骰子。

    我开始认为我想做的事不能在内心完成 tcomb公司 如果是这样的话,我会很惊讶,这样的基本能力没有包括在内。。。

    1 回复  |  直到 10 年前
        1
  •  2
  •   gcanti    10 年前

    README

    const Person = t.struct({
      name: t.String,              // required string
      surname: t.maybe(t.String),  // optional string
      age: Integer,                // required integer
      tags: t.list(t.String)       // a list of strings
    }, 'Person');
    
    // methods are defined as usual
    Person.prototype.getFullName = function () {
      return `${this.name} ${this.surname}`;
    };