Defining a class in JavaScript?

894 views javascript

I was following a tutorial where they used a translator to translate a class in Typescript into javascript. The translated javascript is a bit confusing and I was wondering if someone can explain to me what the code is doing.

Original Typescript:

class Greeter {
    greeting: string;
    constructor(message: string){
        return "Hello, " + this.greeting;

and the translated Javascript:

var Greeter = (function(){
    function Greeter(message){
        this.greeting = message;
    Greeter.prototype.greet = function(){
        return "Hello, " + this.greeting;
    return Greeter;

I am confused about this part (function() { ... }());

what is the first () doing? why is the function(){} necessary? and what is the following () doing?

The syntax is pretty confusing and I hope someone can explain this.

answered question

2 Answers


I am confused about this part (function() { ... }());

IIFE this function will executed as soon as it is interpreted by the browser. You don't have to explicitly call this function.

what is the first () doing? why is the function(){} necessary?

All functions in javascript are Object by nature. To create a instance of it you have to call like new Greeter() so the context this is set properly. If executed like Greeter() now the context this is from where it's executed. In most cases it's the window object.

Reference articles

posted this

This construct:

const foo = (function() { })();

Creates an anonymous function, and immediately calls it. The result gets places into foo.

It's possible to split this up in more lines with an extra variable:

const temp = function() { };
const foo = temp();

The reason typescript does this, is because placing code in function creates its own new scope. This makes it possible to do certain things without changing the global namespace.

posted this

Have an answer?


Please login first before posting an answer.