jQuery in Action, 3rd edition
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
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: 63224

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: person.run(); 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] [Bear's FrontMan] [About Bear] [Books by Bear]
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: "this" in javascript
It's not a secret anymore!