JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
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
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
Creating, Accessing, and Manipulating Arrays
Defining and Calling Functions
Web Browser Supporting JavaScript
Server-Side and Client-Side Web Scripting
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 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