Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
Explain compiled TypeScript namespace (inner working of namespace)

I'm trying to understand how can namespace be implemented in JavaScript. I'm checking out How do I declare a namespace in JavaScript?.

One of the answers mentioned the following TypeScript code.

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

Stack.hello()

is compiled to the following JavaScript

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

However, I find it hard to understand the above syntax, could someone explain how does it work? For example, how does the following work?

(function(Stack) {...})(...)
(Stack || (Stack = {}))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

Stack.hello();

It's a self-executing anonymous function. You can check this document for some insights.

For a more understanding version, you can imagine it like below

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda