构造函数
带字段的类型在创建值时可以接受其中任意字段。construct 代码块用于限定范围:它列出调用方可以传入的字段,其余字段则成为该值自身的状态。
<import package="KScript.Math" />
<type name="Point">
<construct>
<field name="x" type="number" />
<field name="y" type="number" default="0" />
<do>.length = (.x * .x + .y * .y)->sqrt()</do>
</construct>
<field name="length" type="number" />
</type>
<let name="point" value="Point(x: 3, y: 4)" />
<echo>{$point.x}, {$point.y} is {$point.length} from the origin</echo>import KScript.Math
type Point {
construct({
x: number,
y: number = 0,
}) {
.length = (.x * .x + .y * .y)->sqrt()
}
length: number
}
$point = Point(x: 3, y: 4)
echo "{$point.x}, {$point.y} is {$point.length} from the origin"- 花括号中的字段与其他字段的写法相同,以逗号分隔。较短的列表可以写在一行内:
construct({ name: string })。 - 之后的代码块是可选的。每次创建一个值时它都会运行一次,并且是在传入的字段检查之后运行,它可以设置该类型的任意字段。
construct之外的字段以其默认值开始。若没有默认值,则以空值开始:0、''、false、[]、{ }或null。- 传入
construct未列出的字段会报错,错误信息会列出它所接受的字段。编辑器会在你输入时报告该错误。 - 联合类型会先运行其基类的
construct代码块,然后再运行自身的代码块。
类型为model的输入可以默认使用路由所持有的记录。@inject()会从输入的类型读取模型,并使用与输入同名的路由参数:
<type name="PostSummary">
<construct>
<field name="post" type="Post" default="@inject()" />
<do>.words = .post.body->split(' ')->count()</do>
</construct>
<field name="words" type="int" />
</type>
<!-- a controller on /posts/{post} -->
<fn name="stats" value="PostSummary()" />type PostSummary {
construct({ post: Post = @inject() }) {
.words = .post.body->split(' ')->count()
}
words: int
}
// a controller on /posts/{post}
fn stats() => PostSummary()@inject(can: read) 在记录生成时询问模型的策略:construct({ post: Post = @inject(can: read) })。
PostSummary(post: $other) 仍会接收传入的内容。在没有任何路由被响应的情况下,省略该输入会报错并指明该输入。规则详见获取路由记录。
组件使用同一个代码块,将页面可以设置的属性与其保存的状态分开。