davej Posted June 26, 2012 Share Posted June 26, 2012 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 More sharing options...
justsomeguy Posted June 26, 2012 Share Posted June 26, 2012 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 More sharing options...
davej Posted June 26, 2012 Author Share Posted June 26, 2012 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 More sharing options...
Ingolme Posted June 26, 2012 Share Posted June 26, 2012 "this" refers to the element that has the onclick property. Link to comment Share on other sites More sharing options...
niche Posted June 26, 2012 Share Posted June 26, 2012 (edited) This may help. It's on point and the longest topic I've ever started (50 posts). http://w3schools.inv...pic=38677&st=40 It's from my scrapbook. Edited June 26, 2012 by niche Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now