Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with:

THIS, Function Context, And Object Literals In Javascript

By Ben Nadel on

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

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.

Reply to this Comment

@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.

Reply to this Comment

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.

Reply to this Comment

@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.

Reply to this Comment

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

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
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.