THIS, Function Context, And Object Literals In Javascript

Posted October 13, 2009 at 8:42 AM by Ben Nadel

Tags: Javascript / DHTML

In Javascript, the "this" keyword points to the context of the currently executing function. Previously, I had thought that "this" would only work at the object level (treat the object as the context) if the given object was created using the "new" operator. Last night, while finishing up jQuery In Action, I found out that this is not true. A function's context will correctly bind to the parent object even if that parent object is defined as an object literal.

To see this in action, take a look at the following example:

  • <!DOCTYPE HTML>
  • <html>
  • <head>
  • <title>Function Context And Object Literals</title>
  • <script type="text/javascript">
  •  
  • // Define an object literal with properties as well as
  • // a few accessor (getter) methods. Notice that the
  • // accessor use the THIS reference, which will properly
  • // define the context as the parent object, "girl".
  •  
  • var girl = {
  • name: "Phoebe",
  • hair: "Brunette",
  •  
  • getName: function(){
  • return( this.name );
  • },
  • getHair: function(){
  • return( this.hair );
  • }
  • };
  •  
  •  
  • // Call one of the object methods to see what the given
  • // function context is (what the THIS will point to).
  •  
  • console.log( girl.getHair() );
  •  
  • </script>
  • </head>
  • <body>
  • <!--- Nothing here. --->
  • </body>
  • </html>

As you can see, we are creating the object - girl - as an object literal using JSON (Javascript Object Notation). The object contains two properties and two accessor methods. The accessor methods both make reference to the "this" keywords which points to the function context. Because the context properly binds to the parent object - girl - calling the accessor method in the code above returns the corresponding property:

Brunette

That's good to know. I think I still prefer creating objects using Function definitions and the "new" operator as it provides a mechanism for multiple instantiation; but, when I need a really lightweight object definition, this seems like a nice approach.




Reader Comments

Oct 13, 2009 at 9:56 AM // reply »
33 Comments

I absolutely does, and is quite useful. Where things get hairy is that jQuery callbacks alter the THIS scope, and it varies based on what the function executing the callback is (eg. $.ajax success callback, THIS = the ajax parameter object).

This is pretty easily solved by keeping a copy of THIS in a variable (eg. var __this = this;), and from there closures can bubble back up the parent to get to the original THIS via our copy.

Good stuff, and keep up the blogging Ben.


Oct 13, 2009 at 11:13 AM // reply »
11,246 Comments

@Adam,

Yeah, the jQuery stuff is cool though. I think you just start to get used to it. Once you accept the fact that "this" rarely points to the jQuery collection (outside of plugin development), you kind of just assume the next most appropriate thing - the raw element in question.


Oct 13, 2009 at 4:21 PM // reply »
1 Comments

Right, 'this' is determined at the time a function is called. It has no relation to how the object is created or what type of object it is.

When you call any function using foo.bar() notation, 'this' is the foo object.

It also works the same way when you call the function with foo['bar']() or foo[variableContainingMethodName]() notation.

You lose the connection to the original object if you take a reference to the function:

var moo = foo.bar;
moo(); // 'this' is the window object!

As you know, you can also explicitly set 'this' at the time you call a function:

bar.apply( someObject ); or
bar.call( someObject, arg, arg );

Inside the 'bar' function, 'this' will be the someObject you passed in.


Oct 15, 2009 at 8:32 AM // reply »
11,246 Comments

@Michael,

I rather like this. ColdFusion works in the same way - functions are given context only when they are called as a member of a given object.

For some reason, I just had it in my mind that if an object wasn't created using new/() then it would be bound to the window.

This is way cool though.


Jul 1, 2011 at 2:30 PM // reply »
1 Comments

Ben,

This is quite informative. So I thought maybe you can help me. My question may sound silly, but I am having trouble with "this" in Javascript.

I got hold of a JS library on the net for drawing lines, ellipses etc. I want to customize it to add hover effect. So what I did is to copy an existing function - say function abc() and then renamed it to say function xyz(). The original function is accessed by the code as "this.abc". When I try to access the new function as "this.xyz", it throws error saying "this.xyz" is not a function. If I remove "this" and just use xyz, it fires. But again, inside the function when I try to access any property with "this.", it shows up as undefined.

Can you throw some light on this?

Thanks,
Sudhir


May 8, 2012 at 3:17 AM // reply »
1 Comments

thanks Mr.Ben


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 23, 2013 at 9:52 PM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Muhmmadibn Did you figure out a solution to launching PDFs? I am running into the same issues myself. There is no way to close the PDF or go back once you launch it. Thanks in advance! ... read »
May 23, 2013 at 6:06 PM
The Girl Who Broke My Heart, And Made Me A Better Person
Good day,ladies and gentle men, my name is Dr AMADI the great spell caster in Africa, i have help so many people for different kind of problems,who say there is no solution to problems on earth, that ... read »
May 23, 2013 at 4:26 PM
ColdFusion QueryAppend( qOne, qTwo )
@Heather, Glad people are still getting value out of this! ... read »
May 23, 2013 at 3:49 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, I meant the code at the bottom (not the video). I did try to experiment with an intermediary variable, like: value = users.id[ i ]; arrayContains( userIDs, value ); ... but t ... read »
May 23, 2013 at 11:06 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Are you talking about As Number: YES As String: YES As Java: YES? If so, that's with 3 different ways of referencing the constant 1, not users.id[1]. Query object references(*) are what seem ... read »
May 23, 2013 at 9:55 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dan, According to the CF Admin, I'm running Java "1.6.0_45". As far as the DB column, in the database it's an INT. I'll see if I can dig into what CF sees it as. @WebManWalking, But h ... read »
May 23, 2013 at 9:49 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, I think the problem is that we're used to loose typing in ColdFusion, like JavaScript. If a value is a number but it's needed in an expression to be a string, noooo problem. I've encountered ... read »
May 23, 2013 at 9:47 AM
ColdFusion QueryAppend( qOne, qTwo )
You rock! Thank you, thank you, thank you!!! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools