I'm having really hard to really grasp everything about the this object in javascript. I've been trying with tutorials but I haven't found a really good one. I mean, if I have a function which executes some code and then in the end I return "this" what exactly do I then return?

Recommended Answers

All 10 Replies

I'm having really hard to really grasp everything about the this object in javascript. I've been trying with tutorials but I haven't found a really good one. I mean, if I have a function which executes some code and then in the end I return "this" what exactly do I then return?

"this" is contextual rreferer, just like in the normal speech.
Therefore the 'this' keyword property will depend on the executional context. That is, the current owner of the action.

When there is no other context, it will point to hte global object which is the window object.

for instance if you state "this" outside of any function or any other scripting context, the 'this' keyword will point to the current 'window' or the current 'frame', that is the owner of the document.

If inside the function, 'this' will point to the current function object, or if it's used in context of an event, it will point to the object that triggered that event, etc...

Gunnarflax,

Most object-oriented languages have Classes; reusable blocks of code which define a named collection of properties and methods.

Once a Class is defined, one or more instances thereof can be created with a code statement, typically of the form foo = new Bar(param1, param2 ....) ;, where Bar is the name of the Class and foo is a symbol representing the created instance of the Class.

Javascript doesn't have Classes but achieves (arguably) the same nett effect using "constructor functions" the overall form of which is identical to normal Javascript functions. A constructor is characterised (chiefly) by:

  • internally: the use of this
  • externally: calls of the form foo = new Bar(param1, param2 ....) ;

this is simply a keyword used within a constructor function that represents "self" from the point of view of each instance of the constructor. this is necessary because otherwise an instance of a constructor would not have access to its own properties and methods. return this from a constructor is not necessary as this is returned by default, when the constructor is called with the new keyword. A constructor can alternatively (and rarely in my experience) explicitly return something other than this to override the default behaviour. That might be performed, for example, where the constructor needs to return a modified variant of a native Javascript object, or a modified variant of another programmer-defined constructor.

Somewhat confusingly, in a browser environment, this is also used in a different context. Take the following HTML tag for example :

<select onchange="handler(this)">...</select>

Here, this refers to the Document Object Model (DOM) node that corresponds to the select tag. Hence handler is given access (pragmatically speaking) to the select tag (and hence its options/values) without needing to resort to document.getElementById() to 'discover' the DOM node for itself.

Hope this helps

Airshow

But if I have an anchor with onmouseover="function(this)" it would then send the anchor element itself to the constructor right? But if in the function alert(this) I receive "[object Object]" instead of the correct html element. Why is this?

But if I have an anchor with onmouseover="function(this)" it would then send the anchor element itself to the constructor right? But if in the function alert(this) I receive "[object Object]" instead of the correct html element. Why is this?

Because this only refers to the anchor element in the context of the anchor element. In the function, your reference to the anchor element is determined by the formal parameter specified in the function definition. For example :

function f(element){
  //here 'element' refers to the DOM node passed in as a formal parameter.
  //here, 'this' will typically not be used unless f is a constructor (typically called with 'new').
}

Airshow

so what you're saying is that if write:

function(){
   var id = getElementById(this.id);
}

I would get the anchor element in question? Or am I completely lost?

Or am I completely lost?

I'm afraid you probably are Gunnar :(.

By using this in the html onmouseover="f(this)" , you avoid needing to use document.getElementById() in the handler f().

In my example above, this becomes element within f(). Don't use this inside f().

Airshow

But if I have an anchor with onmouseover="function(this)" it would then send the anchor element itself to the constructor right? But if in the function alert(this) I receive "[object Object]" instead of the correct html element. Why is this?

As I've already mentioned: "this" a contextual pointer.

It only points to the current contextual object/subject of the execution.

Thake this example:

var mydiv=document.getElementById('mydiv');
      function alertThis(){ alert(this) }
mydiv.onclick = alertThis;

This time, the "this" keyword becomes a contextual pointer of the of the object that owns the onclick event and will correctly alert you: "object HTMLDivElement"

Ok, I now know why I couldn't test it properly to understand it myself. I'm currently trying to create my own collection of functions which I have inside an object, lets call it eg, so it is sort of my own library. And when I called the function in the anchor it looked like this: onClick="eg.function(this)". It didn't work sending this then but now it does when I have the function outside of the object. When I send it through eg does it send the object eg in the function instead of the html element?

And when I called the function in the anchor it looked like this: onClick="eg.function(this)".

I appreciate that you may be paraphrasing your code, but just in case ..... never name a function function . Both function and Function are reserved keywords in Javascript, and both are used to define functions, not to call them.

When I send it through eg ...

You are not sending anything 'through' eg . eg is merely a container for your handler (and other members presumably). Make sure your handler is appropriately named and actually exists within eg . The definition of the handler will be elsewhere - (probably) where eg is defined.

... does it send the object eg in the function instead of the html element?

No. You only need eg because you have chosen to bundle your handler inside the eg object. Without eg. , the onClick statement would not know where to find the function.

I'm currently trying to create my own collection of functions which I have inside an object, lets call it eg, so it U sort of my own library.

My final words
I don't want to discourage you but you may be trying to run before you can walk. You really need to grasp the basics of programming/Javascript before trying something advanced like composing your own library.

Airshow

What he said(airshow), plus:
example:
HTML

<a href="somepage.html" id=foobar title="this is an href" onmouseover="subby(this);"></a>
<SELECT name=foo id=foo onclick="somesub(this);"><option value=1>one</option></select>

JAVASCRIPT:

function somesub(obj){
   var str='';
   str+='Selected option value is '+obj.options[obj.selectedIndex].value+'<br>';
   str+='Selected option text is '+obj.options[obj.selectedIndex].text+'<br>';
   str+='Total options :  '+obj.length+'<br>';
// etc
}
function subby(obj){
   var mylink=obj.href;
   var mytitle=obj.title;
   var myid=obj.id;
   var mylinktext=obj.innerText;
}

while most of the attributes of the objects above return text values, objects can also have attributes which are themselves objects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.