File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes HTML, CSS and JavaScript and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark ""this" in javascript" Watch ""this" in javascript" New topic

"this" in javascript

Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
Hi I was reading up on creating objects in javascript and I am a bit confused with the "this" keyword.
Normally in C++ and java the this keyword refers to the current "instance" of the class what about javascript. As in this example

does "this.state" statement create a member variable ?? Some articles say its the window object. But I am confused any help or suggestions would be appreciated..
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63873

The worse thing you can possibly do in trying to understand JavaScript is to try to pretend it's Java. (Or C++) It's not. Not even close.

Within a JavaScript function, the this reference is called the function context. And unlike in non-functional languages such as Java, what the function context refers to is not a factor of how the function is declared, but on how it is called.

When using JavaScript in an object-oriented fashion, it's customary to call the method through its reference. In your example, that would be:; And in that case, this will point to person.

However, calling the function in other ways will result in a different function context. It could be window, or it could actually be any object of your choosing.

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: "this" in javascript
It's not a secret anymore!