javascript - TypeScript compiled module declares var before auto invoking function -


i porting existing angularjs (1.x) project typescript, far code working, i'm wondering why happening.

in javascript declaring module so:

(function() {     'use strict';     angular.module('mymodule', []); })(); 

in typescript so:

module mymodule {     'use strict';     angular.module('mymodule', []); } 

which compiled this:

var mymodule; (function (mymodule) {     "use strict";     angular.module("mymodule", []); })(mymodule || (mymodule = {})); 

i have few doubts:

  1. isn't wrong add global scope var mymodule?
  2. why mymodule being passed anonymous function?
  3. since var mymodule added, wonder if should avoid overwriting. separate module declaration from, say, controller. wonder, when declare controller, should use different module name?

in other words, can reuse same name second module, so

module mymodule {     angular       .module('mymodule')       .controller('mycontroller'); } // "overwrite" preexisting var mymodule 

or better use name module, so:

module mymodulecontroller {     angular       .module('mymodule')       .controller('mycontroller'); } // generate var mymodule 

i have seen code works equally fine, i'm sure there things should know on matter.

it's doing you'll able access module other places, example:

module modulea {     export var num = 4; }  module moduleb {     export function log() {         console.log(modulea.num);     }  } 

you can add more same module:

module modulea {     export var num = 4; }  module modulea {     export var str = "string"; }  console.log(modulea.num); // 4 console.log(modulea.str); // string 

in compiled js in example mymodule being passed new definitions added existing module if there one, or {} if not.
compiled js in (2nd) example is:

var modulea; (function (modulea) {     modulea.num = 4; })(modulea || (modulea = {})); var modulea; (function (modulea) {     modulea.str = "string"; })(modulea || (modulea = {})); 

as can see in 2nd time modulea won't empty , adding str variable done on previous defined module.

note behavior true when you're not using module system, example this:

export module modulea {     export var num = 4; } 

compiles into:

define(["require", "exports"], function (require, exports) {     "use strict";     var modulea;     (function (modulea) {         modulea.num = 4;     })(modulea = exports.modulea || (exports.modulea = {})); }); 

(with default module system)


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -