Introduction
One of the most important concepts to grasp in TypeScript is the use of the "this" keyword, which is used in object methods. The "this" keyword always points to the object that is calling a particular method.
The type of "this" in an expression depends on the location in which the reference occurs:
-
In a constructor, member function, or member accessor, this is of the class instance type of the containing class.
-
In a static function or static accessor, this is of the constructor function type of the containing class.
-
In a function declaration or a standard function expression, this is of type Any.
The following example shows how to use the "this" keyword in TypeScript. In this example we have used two classes, one is Base class() and the second is Drive Class(). The Base Class is inherited by the Drive Class. The Base Class has a show method. We are using the show method in the Drive Class using the "this" keyword. Let's use the following procedure.
Step 1
Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is opened. In this window, click HTML Application for TypeScript under Visual C#.
Give the name of your application as "This_keyword" and then click ok.
Step 2
After this session the project has been created; a new window is opened on the right side. This window is called the Solution Explorer. The Solution Explorer contains the ts file, js file, and css files.
Coding
this_keyword.ts
- class Base
- {
- show()
- {
- var x=20;
- alert("This is show method of base class " + x);
- }
- }
- class drive extends Base
- {
- display()
- {
- var y = 10;
- this.show();
- alert("This is display method of drive class " + y);
- }
- }
- window.onload = () =>
- {
- var greeter = new drive();
- greeter.display();
- };
Demo.aspx
- <!DOCTYPEhtml>
- <htmllanghtmllang="en"xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <metacharsetmetacharset="utf-8"/>
- <title>This Keyword TypeScript</title>
- <linkrellinkrel="stylesheet"href="app.css"type="text/css"/>
- <scriptsrcscriptsrc="app.js"></script>
- </head>
- <body>
- <h2>This keyword in TypeScript</h2>
- <dividdivid="content"/>
- </body>
- </html>
app.js
- var __extends = this.__extends || function (d, b) {
- function __() { this.constructor = d; }
- __.prototype = b.prototype;
- d.prototype = new __();
- };
- var Base = (function () {
- function Base() { }
- Base.prototype.show = function () {
- var x = 20;
- alert("This is show method of base class " + x);
- };
- return Base;
- })();
- var drive = (function (_super) {
- __extends(drive, _super);
- function drive() {
- _super.apply(this, arguments);
-
- }
- drive.prototype.display = function () {
- var y = 10;
- this.show();
- alert("This is display method of drive class " + y);
- };
- return drive;
- })(Base);
- window.onload = function () {
- var greeter = new drive();
- greeter.display();
- };
-
Output 1
Click on the "Ok" button:
Output 2
Reference By