Jump to content

Javascript "this"


davej
 Share

Recommended Posts

I have not used "this" in JS and it seems a bit confusing because I'm not sure we are always dealing with objects here. Is an HTML tag an object? Some examples look rather strange. At http://www.quirksmode.org/js/this.html the following code is suggested...

 HTML:element.onclick = doSomething; Javascript:function doSomething(){this.style.color = '#cc0000';}

Ok, since no parameter is passed "this" is what? The current document? The HTML document? The HTML tag? Isn't there a more clear and obvious way to accomplish the same thing?

Link to comment
Share on other sites

I'm not sure we are always dealing with objects here.
We are. In Javascript, even a function is an object.
Is an HTML tag an object?
Strictly speaking, the "tag" is the text. The element itself is in fact represented with an object in the DOM (document object model).
Ok, since no parameter is passed "this" is what? The current document? The HTML document? The HTML tag? Isn't there a more clear and obvious way to accomplish the same thing?
It changes. Technically speaking it is the scope that the function is executing in. In that example, it is the element that the event handler is running on. By default the scope is the window object.
Link to comment
Share on other sites

So if I use window.onload to assign a button to an onclick function then inside that function "this" is the button? I have used event.target to identify which element called a function.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...