函数调用与属性和回调具有相同的名称解析规则。在不带元素名称调用时:
- 如果调用该函数的元素(
self)定义了具有该名称的函数,则选择该函数。 - 如果没有,名称解析将继续到其父元素,依此类推,直到根组件。
在使用元素名称(或 self、parent 或 root)调用时,函数必须在该元素上定义。在这种情况下,名称解析不会查看祖先元素。请注意,这意味着不带元素名称调用函数不等同于使用 self 调用它(这是许多语言中方法的工作方式)。
允许在同一组件中存在多个具有相同名称的函数,只要它们在不同的元素上定义。因此,函数可以遮蔽来自祖先元素的另一个函数。
slint
export component Example { property <int> secret_number: my-function(); public pure function my-function() -> int { return1; }
VerticalLayout { public pure function my-function() -> int { return2; }
Text { text: "The secret number is " + my-function(); public pure function my-function() -> int { return3; } }
Text { text: "The other secret number is " + my-function(); } }}在上面的示例中,属性 secret_number 将被设置为1,文本标签将显示“The secret number is3”和“The other secret number is2”。