0

very simple question...

would like to know what the

"this" variable represents in javascript... thanks

5 Answers5

1

The explanation on quirksmode.org might be a good start.

There is also a nice answer by Alan Storm here on stackoverflow.

Community
  • 1
  • 1
Wolfram
  • 8,044
  • 3
  • 45
  • 66
1

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)
Jakob
  • 24,154
  • 8
  • 46
  • 57
0

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.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
0

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

JohnP
  • 49,507
  • 13
  • 108
  • 140
0

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

Ghyath Serhal
  • 7,466
  • 6
  • 44
  • 60