To elaborate a bit, "this" is special, but it's not magic.
 
Whenever you call a function in JavaScript, it's always called as a method
of some object, and this is a reference to that object.
 
When you call foo.bar(), you are calling a function as a method of the foo
object, so this == foo.
 
JavaScript also has a global object. When you call a function bar() without
any explicit object reference, you are actually calling it as a method of
the global object.
 
The global object in a browser happens to be the window object. That's why
you find this == window when you call a function without an object
reference.
 
In other places where JavaScript is used, the global object may be something
else. For example, in Acrobat and Adobe Reader, the global object is the doc
object, which is a reference to the current PDF document. So in a PDF file,
when you call a function without an explicit object reference, this == doc.
 
Even though there are different global objects in these different
environments, JavaScript follows the same principles regardless. this is
either a reference to the object you explicitly specified, or to the global
object.
 
Does that help explain this? :-)
 
-Mike



  _____  

From: Michael Geary
 
"this" is special: its definition depends on how a function was called.

Reply via email to