在Monkey C之中,呼叫一個function時會依循一套由近到遠的規則去尋找function,
先後順序如下:
1.類的實例成員
2.超類(繼承的父類別)的成員
3.類的靜態成員
4.父模組的成員,到全域命名空間
5.超類的父模組的成員,到全域命名空間
官方範例如下:
using Toybox.System;
// A globally visible function
function globalFunction() {
System.println("This is the global function!");
}
module Parent
{
function parentFunction() {
System.println("This is the parent's function!");
globalFunction(); // May call a globally visible function
}
class Child {
function childFunction() {
System.println("This is the child's function!");
globalFunction(); // May call a globally visible function
parentFunction(); // May call a function in our parent module
staticChildFunction(); // May call a static function within the class
}
static function staticChildFunction() {
System.println("This is the child's static function!");
globalFunction(); // May call a globally visible function
parentFunction(); // May call a function in our parent module
// Static methods can't call instance methods (childFunction) but still have access to parent modules!
}
}
}
如果要指定使用global function,可以使用$.
來直接呼叫global function,
就算class內沒有相同名稱的function,如果呼叫global function,還是加$.
比較好,
除了避免掉執行時Monkey C到處搜尋這個function耗費的效能,
也方便其他人閱讀程式碼,可以很直觀的知道呼叫的是global function
using Toybox.System as System;
var familyFortune = "There's always money in the banana stand.";
module BluthCompany
{
class BananaStand {
function getMoney() {
// At runtime, the VM will search:
// 1. The BananaStand
// 2. The BananaStand's superclass, Toybox.Lang.Object
// 3. The BluthCompany module
// 4. The BluthCompany module's parent globals
// ...and finally finds the family fortune!
System.println(familyFortune);
// This will search only the global namespace for the family fortune. Thanks bling!
System.println($.familyFortune);
}
}
}