Estoy tratando de entender cómo se puede implementar el espacio de nombres en JavaScript. Estoy revisando ¿Cómo declaro un espacio de nombres en JavaScript? .
Una de las respuestas mencionó el siguiente código TypeScript.
namespace Stack { export const hello = () => console.log('hi') } Stack.hello()está compilado en el siguiente JavaScript
var Stack; (function (Stack) { Stack.hello = () => console.log('hi'); })(Stack || (Stack = {}));Sin embargo, me resulta difícil entender la sintaxis anterior, ¿alguien podría explicar cómo funciona? Por ejemplo, ¿cómo funciona lo siguiente?
(function(Stack) {...})(...) (Stack || (Stack = {})) var Stack; (function (Stack) { Stack.hello = () => console.log('hi'); })(Stack || (Stack = {})); Stack.hello();Es una función anónima autoejecutable. Puede consultar este documento para obtener algunas ideas.
Para una versión más comprensiva, puedes imaginarlo como a continuación
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();