amitte Posted December 11, 2009 Report Share Posted December 11, 2009 Click on this text Quote Link to comment Share on other sites More sharing options...
falkencreative Posted December 11, 2009 Report Share Posted December 11, 2009 Someone else may be able to explain this better... Basically, it's a way to allow Javascript to target specific elements. In this case, this "this" refers to the the element that called the function. In this case, the "this" refers to the , so the gets passed into the changetext() function and gets changed. If you changed the code to this: Click on this text Now the "this" would refer to the , and if you clicked it, it would change. More info on "this": http://www.quirksmode.org/js/this.html Quote Link to comment Share on other sites More sharing options...
monkeysaurus Posted January 18, 2010 Report Share Posted January 18, 2010 Basically, it's a way to allow Javascript to target specific elements. Yes and no; it's actually much more than that. To understand 'this' in Javascript, you first need to understand that everything in Javascript is an object. Functions, events, DOM elements...all objects. In fact, Javascript is possibly one of the most object oriented languages around. In addition, every object must have an 'owner'. Let's say you're declaring a variable, thusly: var foo = 'bar'; // alerts 'bar' alert(window.foo); Well, you haven't really declared a variable at all! You've attached a property named foo to the window object. In Javascript, if you declare a variable (a function, an object...etc) in the global scope, you've attached an object to the window object. Similarly: foo = function(){ alert('bar'); } window.foo(); // alerts 'bar' this.foo(); // alerts 'bar'! WTF! 'This' in Javascript refers to the current object's owner. So let's take a look at your original question. Click on this text What's happening here is that you are calling a function called changetext, and you are passing the owner object as the parameter. In this case, the owner is the object. So for the following function: function changetext(id) { id.innerHTML="Ooops!"; } ...You have passed in the h1, and you're saying "h1.innerHTML should now be 'Ooops!". Variable scope is one of the trickier aspects to get your head around in Javascript, but once you do, nothing will be the same again. Further reading here. Quote Link to comment Share on other sites More sharing options...
amitte Posted January 19, 2010 Author Report Share Posted January 19, 2010 well Ben Monkey... i want to thank u very much for this clarification!!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.