Reputation: 948
I want to define a class inside an IIFE using TypeScript and keeps getting error, class can be defined either in a module or a file
. Below code does not work.
(function(){
// Error here
class Person {
}
})()
The reason i need to do this is because i don't want to expose any global variables, not even module. You may wonder why, because i would add them to angular modules in below way
(function(){
angular.module('app').controller('HomeController', HomeController);
// error here
class HomeController {
}
})();
Upvotes: 1
Views: 1937
Reputation: 250972
When you create a class, it generates an IIFE for you:
The class:
class Example {
}
Results in the JavaScript:
var Example = (function () {
function Example() {
}
return Example;
})();
If you want to keep your classes out of the global scope, you can use modules:
module Stack {
export class Example {
}
export class Overflow {
}
}
Only the Stack
module appears in the global scope.
var Stack;
(function (Stack) {
var Example = (function () {
function Example() {
}
return Example;
})();
Stack.Example = Example;
var Overflow = (function () {
function Overflow() {
}
return Overflow;
})();
Stack.Overflow = Overflow;
})(Stack || (Stack = {}));
If you want to go a step further, you can use external modules - when you do that, none of your classes or modules is added to the global scope.
Upvotes: 4