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:
- isn't wrong add global scope
var mymodule
? - why
mymodule
being passed anonymous function? - since
var mymodule
added, wonder if should avoid overwriting. separate module declaration from, say, controller. wonder, when declare controller, should use differentmodule
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
Post a Comment