| 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: 56192
|
|
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.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
 |
|
|
subject: "this" in javascript
|
|
|