‘This’ in Javascript and C#

I noticed something today while learning jQuery, and that’s the way the keyword `this` 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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s