• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"this" in javascript

 
Rajesh Khan
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64721
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic