a blog for those who code

Tuesday 21 April 2015

Classes in TypeScript

In this post we are going to discuss about Classes in TypeScript. In simple language Classes helps you to organize your code, it is just a way to organize your fields, properties, functions etc. Classes can consists of Fields, Properties, Constructors and functions.

Before going into the Classes in TypeScript, we should know that Classes in TypeScript actually do not get translated in JavaScript. Classes comes handy at design time to organize your stuff, but once it is compiled to JavaScript you will actually not see any traces of Classes (ES5 or less).

Classes actually consists of Fields (a variable in your class), Constructors (A way to initialize your data), Properties ( Plays intermediary role to a field of the class ) and Functions (To know about functions have a look at Functions in TypeScript).

Example of Classes:

//We start creating classes with a keyword class and then the name of the Class (i.e. Sports) 
class Sports {
  sportName: string; //This is a field or variable
     //Then we have a constructor (constructor keyword is mandatory), its basically used to initialize your class
    constructor(name: string) {
      this.sportName = name;
    }
    //This is a Class Function (More at Functions in TypeScript)
    loveSport() {
      return "I love playing " + this.sportName;
    }
}
//This is the code where we will initialize our class using new keyword
var sports = new Sports("Cricket");

The Compiled JS File

var Sports = (function () {
  function Sports(name) {
      this.sportName = name;
  }
  Sports.prototype.loveSport = function () {
      return "I love playing " + this.sportName;
  };
  return Sports;
})();
var sports = new Sports("Cricket");

Static Members of Classes

Static actually means single instance of class members which is shared and which is very efficient on memory. In JavaScript particularly we have something like prototype, like if you add any function to prototype it is shared across instances of that.

Example :

class Sports {
    //Static Field
  private static sportName: string = "Hi"; 
    //Static Function
  static loveSport() {
   //Getting field by using Class.FieldName (Static Nature)
     return Sports.sportName;
   }
}
//Calling Function using ClassName.FunctionName() without creating an instance of Class
Sports.loveSport();

The Static field will come handy if you have to define some constants in your application, which basically does not change in the course of time.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment