To understand this
you have to understand object oriented programming.
In object oriented programming, most methods (functions) belong to objects
. In Javascript, most objects
are window elements; a button, a list, a div. Almost anything on your web page that you can describe as a noun is probably an object
, in some fashion; and the few things that aren't, are members of objects
.
So, in object oriented programming, you have the problem that you might have a method, say, onclick
. Inside onclick
you have some code that executes; let's say you are changing the background of a <div>
from blue to green and back when it is clicked on. Let's construct that, in english/pseudocode.
myDiv.onClick {
if the div that was clicked on has a background of blue then set that div's background to green
else if the div that was clicked on has a background of green then set it to blue
}
So, pretty easy, right? If this weren't object oriented programming, your function would take an argument, div_id
. So,
onClick(div_id theDiv) {
if theDiv.background=blue then theDiv.background=green
else if theDiv.background=green then theDiv.backgrond=blue
}
However, this is object oriented programming. onClick is a method of the div, and part of the advantage of object oriented programming is that you don't need to pass arguments like which div you mean - the div you mean is the one whose argument was called, of course! Each div has its own reference to onClick, possibly its own copy depending on how you wrote the method.
That does leave a problem, though. How do you say,
if this Div's background is blue then set this div's background to green
?
The answer is this
. this
refers to the object that the current method belongs to. So, when a div is clicked on, its onClick method is called; and you have:
div.onClick() {
if this.background=blue then this.background=green
else if this.background=green then this.background=blue
}
So you only write one div.onClick function, and now every div is able to be turned blue or green at your leisure.