this in JavaScript vs C#

Coming from C#/C++/Java, the usage of the this keyword in JavaScript is confusing. This is my attempt to explain it, in C# terms (with C# being very close to C++ and Java). I’ve thought of writing this post a long time, but it’s just now, when reading JavaScript: The Good Parts that I’ve finally understood it well enough myself to be able to explain it.

In C# (and C++ and Java) the this keyword is available inside any class method and refers to the current object used to invoke the method. When I first started writing JavaScript I assumed that it would be the same, but soon found out that I was wrong. this in JavaScript has a different behaviour.

JavaScript Objects

My first assumption was that inside a method the this keyword would refer to the current object. I was surprised when things didn’t behave as I expected, but it wasn’t this fault. It was my lack of understanding of JavaScript objects and methods. JavaScript is object oriented, but it is a prototypical object orientation which is not at all the same as the class-based object orientation in C#.

JavaScript objects are not like C# objects. A JavaScript object is a simple key-value pair storage, which is much more similar to C# Dictionaries. I’ve found it much easier to understand JavaScript’s objects once I stopped thinking of them as objects and instead thought of them as Dictionaries. In fact, in JavaScript, object.property is just shorthand for object["property"]

// Create an empty object.
var mySelf = {};
// Add a "name" property.
mySelf["name"] = "Anders";
document.write('mySelf["name"] = ' + mySelf["name"] + "<br/>");
document.write('mySelf.name = ' + mySelf.name + "<br/>");

This is the resulting output:

mySelf["Name"] = Anders
mySelf.Name = Anders

Methods

So, if a JavaScript object is a key-value store like C# dictionaries, what about methods? In C# a dictionary is a value storage, there is no such thing as methods in dictionaries unless they store some kind of Action or Func. This is where the different basic concepts once again fool us. First of all, in JavaScript functions are first class objects. This is not the right time to go into details about what that means, so let’s just think of them as a C# delegate to a static method.

An observant reader might think that I just have gone nuts. I have promised to explain this in JavaScript and then I refer to static methods – that completely lacks access to this. I promise, I have not gone nuts. I’m just trying to explain that some core concepts of JavaScript are very different than in C#. Those core concepts affect seemingly simple things like this

A JavaScript method is simply a property of an object, who’s value is a function object. Remember, JavaScript functions are objects and the dynamic typing of JavaScript allows any kind of object to be stored as a property of an object. Let’s augment the mySelf object from the previous example with a sayHello method.

mySelf.sayHello = function() { document.write("Hello!") };

Calling mySelf.sayHello() now adds “Hello!” to the document.

this and Methods

I hope you’re still with me, because it’s now time for looking at the this keyword. From C#, we are used to methods belonging to a class. A method that has access to this must be defined inside the class. In JavaScript the coupling is much looser. The function is an object in itself, which is merely associated to an object. The secret of JavaScript’s this is that it’s not bound to the function itself, but to how it is invoked. The same function will be passed different this values depending on how it’s called. In the simple case where the method is called through a property of an object this behaves just as expected.

Let’s add a getPayment method that receives money for mySelf and updates or creates the mySelf’s cash property as well as a showCash helper that shows the current amount of cash.

var getPayment = function (amount) {
  // Initialize to 0 if no cash property.
  this.cash = (this.cash || 0) + amount;
};
 
var showCash = function() { 
  document.write("Current " + this.name + " cash: " + this.cash + "
"); 
};
 
mySelf.getPayment = getPayment;
mySelf.showCash = showCash;
mySelf.getPayment(10);
mySelf.showCash();

That will create the cash property on the mySelf object as expected, so mySelf.showCash(); will show the expected current cash.

Current Anders cash: 10

That’s all for today. Next time I’ll look into more details on this for methods, closures and what the global object is.

The links to Amazon in this post are sponsored.

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.