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 object:

<html>
<!-- Object_this_Keyword.html
   Copyright (c) 2008 HerongYang.com. All Rights Reserved.
-->
<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.

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

Introduction to Objects

 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

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB