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();