Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Self-Executing Anonymous Functions

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.

like image 750
Mudaser Ali Avatar asked May 16 '15 10:05

Mudaser Ali


People also ask

What is JavaScript self-invoking anonymous function or self executing anonymous function?

A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console.

What is the self executing function?

The self-executing anonymous function is a special function which is invoked right after it is defined. There is no need to call this function anywhere in the script. This type of function has no name and hence it is called an anonymous function. The function has a trailing set of parenthesis.


2 Answers

/**
 * 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)

like image 109
Vadorequest Avatar answered Oct 01 '22 12:10

Vadorequest


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.

like image 31
Adi Avatar answered Oct 01 '22 13:10

Adi