File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark ""this" in javascript" Watch ""this" in javascript" New topic
Author

"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
Marshal

Joined: Jan 10, 2002
Posts: 61415
    
  67

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]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: "this" in javascript