very simple question...
would like to know what the
"this" variable represents in javascript... thanks
very simple question...
would like to know what the
"this" variable represents in javascript... thanks
The explanation on quirksmode.org might be a good start.
There is also a nice answer by Alan Storm here on stackoverflow.
Loosely speaking, it represents what is to the left of the dot when you invoke the function:
// inside of f, this = x
x.f(1, 2, 3)
// inside of f, this = c
a.b.c.f(1, 2, 3)
There are a number of exceptions to the rule.
First, if you have no dot:
// inside of f, this = the global object ("window", if you're in a browser environment)
f(1, 2, 3)
Secondly, you can use the methods call
and/or apply
to explicitly set the value of this
:
// Invokes f with this = myVar, not x (arguments 2 an onward are the ordinary arguments)
x.f.call(myVar, 1, 2, 3)
// Invokes f with this = myVar, not x (arguments are passed as an array)
x.f.apply(myVar, [1, 2, 3])
Third, when you invoke a function using new
, this
will refer to the newly created object:
// inside of f, this = a new object, not x
new x.f(1, 2, 3)
The this
variable in javascript, as in any other language, refers to the current object.
For example:
document.getElementById('link1').onclick = function()
{
this.href = 'http://google.com';
}
In the onclick handler the this would refer to the DOMElement which you got by id.
It's a reference to the current owner of the function or scope we're in.
You can find more info here : http://www.quirksmode.org/js/this.html
In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.
Check the below link for more explanation.
http://www.quirksmode.org/js/this.html