簡體   English   中英

如何在TypeScript中從自身引用匿名模塊?

[英]How do I reference an anonymous module from itself in TypeScript?

我的代碼中存在外部模塊情況。 根據建議(請參閱“不必要的命名空間 ”),我試圖避免不必要的名稱空間,並從各處刪除模塊聲明。 現在,當模塊中函數的參數與模塊中另一個函數的名稱相同時,我會遇到命名沖突。 因此,我希望我能以某種方式告訴編譯器,它不是參數,而是我需要調用的當前模塊中的另一個函數。 考慮:

function a() {
}
function b(a: {}) {
  return a(); /// <--- a problem, I wish there was something like: module.a(); or global::a();
}

有沒有辦法在不更改名稱的情況下克服此問題?

function a() {
}
function b(a: {}) {
  return this.a(); ///try using this
}

我寧願建議這樣做:

module Testing {
    class MyFuncs {
        public a = () => { }
        public b = (a: {}) => { return this.a()}

    }
}

對於模塊,如果導出a函數,則可以通過模塊名稱訪問它。 對於全局項,您需要擴展表示全局根的接口,以使編譯器了解其他項。 我在下面顯示了兩個示例。

// Module
module Example {
    export function a() {
        alert('A1');
    }

    export function b(a: {}) {
      Example.a(); /// <--- I wish there was something like: module.a();
    }
}

Example.b({});

// Global
interface Window {
    a: () => any;
}

function a() {
    alert('A2');
}

function b(a: {}) {
  return window.a(); /// <--- I wish there was something like: global::a();
}

b({});

如果這兩種方法都不適合您,也許可以更改設計以將方法包裝在類中,因為使用this關鍵字訪問類成員可以將它們與局部變量和參數區分開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM