Using this inside an AMD module

Topics: General
Oct 19, 2012 at 2:07 PM


I am trying to use define a self variable in a module so that I can use it as the context in some function inside the module:

export module Module1 { 
 var self = this; 

I am receiving the error Error 5 'this' may not be referenced within module bodies.

How can I make it work ?

Thanks in advance.

Oct 19, 2012 at 4:17 PM

There are a couple reasons why 'this' isn't allowed in a module.  The modules system TS uses is based largely on the ECMAScript version 6 draft.  When modules were being created, the team tried to align conservatively with this draft, which, to my understanding, meant that because the ES6 proposal didn't allow 'this', TS shouldn't either.  The other reason was that the codegen currently doesn't expect 'this' to talk about the module.

That said, these reasons aren't set in stone and could change.

Oct 19, 2012 at 5:52 PM

But I have a function that needs to use the self variable in its context.

How can I do this ?

Oct 19, 2012 at 11:41 PM

There is only one instance of the module, so any reason you cannot just reference "Module1" directly?  If not, could you share an example of what doesn't work?



Oct 22, 2012 at 5:06 PM


Using the nmame of the module worked perfectly.


Nov 3, 2012 at 6:09 PM

Same problem here.

I see no evidence in the ES6 proposal [1] that supports this behaviour. It clearly states: "The initial binding of this is the global object."

Unfortunately in my current situation (Mozilla JS Modules [2]) I need "this" to fake a CommonJS module system, so that I can use TypeScript. Current workaround only seems to be "eval('this')".