Static Method in TypeScript

Static Method in TypeScript

Whenever you want to access methods of a class (but the method of the class is not static), then it is necessary to create an object of that class. But if the static keyword is used with a member function (method), that method is automatically invoked without creating an object of the class, you just invoke that method using the class name .(dot) method name. In short if we say about static methods, the static keyword enables us to use methods of a class without instantiating any object first. In static methods, you can define both static and non-static data members, and you can also use the this keyword in static methods.

Syntax

access modifier static (keyword) MethodName (Parameter (Optional)) {...........//body}

The following example tells you, how to use a static method in TypeScript. Use the following procedure to create a program using a static method.

Step 1

Open Visual Studio 2012 and click on "File" menu -> "New" -> "Project". A window is subsequently opened. Provide the name of your application, like "ExOfstaticMethod", then click on the Ok button.

Step 2

After Step 1 your project has been created. The Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, css file and html files.

Step 3

The code of the static method program:

ExOfstaticMethod.ts

class StaticMethod{

public fname: string;

publicstatic lname: string;

static MyFunction(fname:string)

{

document.write("I am a static member function");

this.fname = fname;

this.lname = "solution";

alert("" + this.fname + " " + this.lname);

}

}

window.onload = ()=>{

StaticMethod.MyFunction("Mcn");
}


Note:
In the above declared program I have create a static method with argument , in this program the static method is called without creating the object of the class.

default.html

 

<!DOCTYPEhtml>

 

<htmllang="en"xmlns="http://www.w3.org/1999/xhtml">

<head>

<metacharset="utf-8"/>

<title>TypeScript HTML App</title>

<linkrel="stylesheet"href="app.css"type="text/css"/>

<scriptsrc="app.js"></script>

</head>

<body>

<h1>TypeScript HTML App</h1>

 

<divid="content"/>

</body>

</html>


app.js

 

var StaticMethod = (function () {

function StaticMethod() { }

StaticMethod.lname = "";

StaticMethod.MyFunction = function MyFunction(fname) {

document.write("I am a static member function");

this.fname = fname;

this.lname = "solution";

alert("" + this.fname + " " + this.lname);

}

return StaticMethod;

})();

window.onload = function () {

StaticMethod.MyFunction("Mcn");
};


Output

static-method-in-typescript.jpg

Up Next
    Ebook Download
    View all

    Test

    Read by 16 people
    Download Now!
    Learn
    View all