JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.10

Using "this" Keyword to Represent Current Object

This section provides a quick description of the 'this' keyword, which represents the current object in object method. A tutorial example is provided on how to access properties and methods of the current object.

While defining a function to be used as a method for objects, you can use the keyword "this" to represent the current object the method is called against. The "this" keyword in JavaScript has the same usage as in Java.

Here is tutorial example of using "this" keyword to access properties and methods of the current project:

<html>
<!-- Object_this_Keyword.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>"this" Keyword in Object Methods</title>
</head>
<body>
<pre>
<script type="text/javascript">

// Using "this" to get the properties
function myToString() {
   return '"'+this.title + '" by '+this.author;
}

// Using "this" to get the "toString" method
function showAll() {
   window.alert(this.toString());
}

   // Preparing one of "Object" type
   var myBook = new Object();
   myBook.author = "Herong Yang";
   myBook.title = "JavaScript Tutorials";

   // Adding a new method to one object only
   myBook.print = showAll;
   
   // Overriding "toString()" on one object only
   myBook.toString = myToString;

   // Calling the method on "myBook"
   myBook.print();
</script>
</pre>
</body>
</html>

If you run this "this" keyword example, you will get an alert box with the message of: "JavaScript Tutorials" by Herong Yang.

Sections in This Chapter

What Is an Object?

Objects of "Object" Data Type

Adding and Deleting Object Own Properties

Adding and Deleting Object Own Methods

Using "this" Keyword to Represent Current Object

Object Literals of the "Object" Type

Objects and Associate Arrays

Objects with Indexed Properties

Differences between "Object" and "Array"

Using "Array" Objects as "Object" Objects

Dr. Herong Yang, updated in 2008
Using "this" Keyword to Represent Current Object