網站搜尋

javascript - 解釋已編譯的 TypeScript 命名空間(命名空間的內部運作)


我正在嘗試了解命名空間如何在 JavaScript 中實現。我正在查看「我如何在 JavaScript 中宣告命名空間?」。

其中一個答案提到了以下 TypeScript 代碼。

namespace Stack {
    export const hello = () => console.log('hi')
}

Stack.hello()

被編譯成以下的 JavaScript

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));

不過,我覺得很難理解上述語法,有人可以解釋它是如何運作的嗎?例如,以下這個是如何運作的?

(function(Stack) {...})(...)
(Stack || (Stack = {}))

答案#1

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));

Stack.hello();

這是一個自執行匿名函數。你可以查看這個文件以獲取一些見解。

為了更容易理解的版本,你可以像下面這樣想像它

var Stack;

//naming the function
//`Stack` here is not related to the global `Stack` because the function parameter scopes this variable
function anonymousFunction(Stack) {
    Stack.hello = () => console.log('hi');
}

//replace for `Stack || (Stack = {})`
if(!Stack) {
   Stack = {} //it's a reference value, so if we have any changes inside a function, it will be applied to `Stack` as well
}

//execute the function/namespace to add `hello` to `Stack`
anonymousFunction(Stack); 

Stack.hello();