Jump to content

what is "this"?


amitte

Recommended Posts

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

Link to comment
Share on other sites

  • 1 month later...
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.

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...