DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. 'this' in JavaScript vs C#

'this' in JavaScript vs C#

Anders Abel user avatar by
Anders Abel
·
Dec. 27, 13 · Interview
Like (0)
Save
Tweet
Share
8.98K Views

Join the DZone community and get the full member experience.

Join For Free

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.



JavaScript csharp Object (computer science)

Published at DZone with permission of Anders Abel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Reliability Is Slowing You Down
  • Container Security: Don't Let Your Guard Down
  • Real-Time Analytics for IoT
  • How To Handle Secrets in Docker

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: