‘This’ in JavaScript and C#

copied from my old blog: http://www.stevecooper.org/index.php/2010/01/16/this-in-javascript-and-csharp/

I noticed something today while learning jQuery, and that’s the way the keywordthis differs between C# and JavaScript. It suprised me when I saw some javascript that looked like;

01 $(document).ready(function() {
02   $(‘div’).each(function() {
03   this.style.color = ‘blue’;
04   });
05 ));

and I realised that this wouldn’t work in C# — at least, not the same way it works in JavaScript. In the JavaScript above, the this on like 03 refers to each div element that’s being iterated over.

Now consider similar C# code;

class Document { 
    List divList = …;
    void Ready() {
        divs.foreach(delegate () { this.style.color = “blue”; });

In C#, this doesn’t refer to the div, but to the Document class.

In both pieces of code, we’re creating a function with a reference to this, but they mean different things;

  • In C#, this means the object that declares the function
  • In JS, this means the object the function is being invoked on.

To see the difference, realize that you can attach the same function to two different javascript objects, and you’ll see this referring to each one in turn. Here’s a piece of javascript to illustrate;

var func = function() { alert(this.name); }
var obj1 = { ‘name’: ‘first object’, ‘func’: func }; 
var obj2 = { ‘name’: ‘second object’, ‘func’: func };
obj1.func(); obj2.func();

When you run this; you get two alerts: first object and second object. But when you run this in C#

Action func = delegate() { MessageBox.Show(this.GetHashCode()); };
var obj1 = new { func = func }; 
var obj2 = new { func = func };
obj1.func(); obj2.func();

You see the same hashcode in both message boxes. It’s the hashcode of the object that contains this method.

So. Don’t confuse the meaning of this in C# and JavaScript. They are very different beasts.

Now, if you want C#’s semantics in Javascript, you have to take account of this behaviour. With my C# head on, I was tempted to understand ‘this‘ as a variable name, but it isn’t. It’s a keyword, and not a variable name. To make it work like C#, you need to create a real variable, and use the variable in the function. Like so;

var outerThis = this; // declare a real variable
func = function() { alert(outerThis.name); }

And this will give you C# semantics in Javascript.