10

How I can create self-executing anonymous functions using type script?

For example

(function() {
 var someClass = {
 }
}.call(this));

I want a built a plugin that may work for Node.js, also for fron-tend as well.

2
  • no because all answers cannot produce about output Commented May 18, 2015 at 11:19
  • I actually don't understand what you mean by that. Commented May 18, 2015 at 17:23

4 Answers 4

38
/**
 * Self executing anonymous function using TS.
 */
(()=> {
    // Whatever is here will be executed as soon as the script is loaded.
    console.log('executed')
})();

I want a built a plugin that may work for Node.js, also for fron-tend as well.

In that case you should compile your TypeScript in AMD and use an AMD loader on the frontend, like http://requirejs.org/docs/start.html

On the server side, you would need to use requirejs node package as well to load the file. Take a look at this: http://requirejs.org/docs/node.html

Basically there are two ways to compile TS to JS, using AMD, which is browser compliant, or using CommonJS, which is node.js compliant. Loading an AMD script in the browser or in the server needs to use an AMD compliant loader, and *requirejs** is one of them. (the most famous/used I'd say)

3

First rule in TypeScript: Any valid JavaScript is valid TypeScript.

No, there are are no special way to write Self-Executing Anonymous Functions in TS as of right now.

But, below is some code that might be of some use in your situation.

Every Class in TS is compiled to a (Named) Self-Executing Anonymous Functions, which returns a function.

Example:

//ts
class someClass {
  someProperty = "this is a property";
}

Translates to

//js
var someClass = (function () {
    function someClass() {
        this.someProperty = "this is a property";
    }
    return someClass;
})();

Hope this is of some help.

1
  • 1
    I wish the Any valid JavaScript is valid TypeScript rule was true. TypeScript is great but I get soo frustrated with type exceptions for perfectly valid JavaScript... I am currently researching how to create jQuery plugs in TypeScript... Nightmare! Commented Mar 30, 2018 at 8:57
0

An self-executing, immediate, recursive top-level React function in Typescript:

(function handleAutomatonTypeChange(newtype: AutomatonType) {
  ReactDOM.render(
    <Automaton automatonType={newtype}
               onAutomatonTypeChange={handleAutomatonTypeChange} />,
    document.getElementById('automaton')
  );
})('diadic');
-3
(function(){
    document.body.innerHTML = "Self Calling Function";
}.call(this));
1
  • 4
    Please edit your answer to include some explanation. Code-only answers do very little to educate future SO readers. Your answer is in the moderation queue for being low-quality. Commented Apr 22, 2017 at 4:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.