私有字段和方法
在字段或方法前加上 private,即可将其限制在该类型内使用。只有该类型自身的方法、其 construct 代码块,以及(对于组件而言)其 render 可以访问它。
<type name="Counter">
<construct>
<field name="start" type="int" default="0" />
<do>.count = .start</do>
</construct>
<field name="count" type="int" private="yes" />
<fn name="doubled" value=".count * 2" private="yes" />
<fn name="total" value="$this->doubled() + .count" />
</type>
<let name="counter" value="Counter(start: 2)" />
<echo value="$counter->total()" />type Counter {
construct({ start: int = 0 }) {
.count = .start
}
private count: int
private fn doubled() => .count * 2
fn total() => $this->doubled() + .count
}
$counter = Counter(start: 2)
echo $counter->total()- 类型之外的代码无法读取私有字段(
$counter.count)、为其赋值、在创建值时传入它,也无法调用私有方法($counter->doubled())。kscript check会报告每一项,同样的错误也会中止正在运行的脚本。 - 私有字段在显示值或转换为 JSON 时会被省略,因此
$counter->convert(to: json)为{"start":2}。 - 方法可以访问同类型另一个值的私有成员,例如
fn same(other: Counter) => $other.count == $count。 - 联合类型使用其所基于类型的私有成员。
- 编辑器只在类型内部提供私有成员。
- 在模型上,私有字段仍然是一列。它照常存储和加载,只有模型自己的方法会读取它。
- 没有
public,因为其他成员本来就是这样。
private关注的是其他代码可以使用什么,而不是保密。实时组件的状态,无论是否私有,都会带签名地传到浏览器再传回来。