Javascript Object Inheritance that C#/Java Coders can Understand

February 18, 2014 at 10:22 am (Computer Science, JavaScript, Programming, Teaching) (, , , , , , )


So, at work I’ve been using Javascript as a primary language for a while now. While I am likely not an expert, I’ve picked up some neat tricks. Since I work with an office full of C# coders, I need to write code that they can understand quickly. Therefore, one of my first motivations is to write code that can be understood by non-Javascript purists.

So let’s build a simple example of how to achieve objects and inheritance using Javascript. While there are more than one way to create objects in Javascript, I’ve been using this approach as several good/reputable sources have suggested it, and it resembles C#/Java somewhat. Note: I don’t condone the act of trying to make Javascript into a language it isn’t, but I do support readability. In this case, our reader understands a separate language and they have no reason/incentive to learn ours. So we will commit as few crimes as possible to make our code understandable by people that don’t know Javascript.

So here is our base case: Shape. It holds a position coordinate with a public accessor.

function Shape() {
  var _x = 0,
      _y = 0;  
  /**
  This acts as a constructor for us and looks familiar-ish to C# coders. 
  */
  initializeComponent() {
      _x = 5;
  }
  
  this.getX = function() {
    return _x;
  }

  this.getY = function() {
    return _y;
  }

  /**
  Can't forget to call our own constructor.
  */
  initializeComponent();}

So this is our base class. We’ve defined X and Y and Javascript will treat them as private variables. When you instantiate the object, you can only access them via the public “GetX()” method (I’ll show instantiation shortly). You will also notice the function “initializeComponent”. This is what I call a constructor, but I stick to this function name just by convention. You can call it whatever you want, within reason; Javascript reserves some keywords. You’ll see at the bottom of the class that we are calling this constructor ourselves. What’s with that?? Well, to Javascript, the whole class is a constructor, but if we had our code spilling everywhere then it would be messy and not at all like C#.

The last thing to notice is that our public accessors are attached to a “this” keyword. “This” will refer to the instantiated object, and the function will attach itself as a property of that object. This is different from our private variables, which aren’t properties of the object, but are accessible from within those public functions. Without getting into details, this essentially lets us mimic the behaviour of C#/Java.

Now to the good part: we want to instantiate our object!

var ourObject = new Shape();
ourObject.getX(); // This returns _x
ourObject._x; // This returns undefined as it is not accessible

So this is how to instantiate the object. Everything works as expected. Now lets talk about how to make a new class that inherits from Shape. Incoming code:

function Circle() {
  var _r = 0;
  this.GetRadius = function() {
    return _r;
  }
}
Circle.prototype = new Shape;
Circle.prototype.constructor = Circle;

Okay, so we’ve seen everything in Circle already, but what is that noise after the class definition? So again, without getting into details (which are already everywhere on the interwebs), the first line is setting the class to inherit from. This means that if you instantiate Circle, you can do operations such as:

circle.getX();

This is a valid operation. Exciting. Now what was that second line? We need to set the prototype’s constructor to point back to our Circle class. This allows us to use the “instanceof” operator and have it work as we would expect. Now, it isn’t necessary to do this step, but it plays nice when other people use our code.

So that’s how we can achieve something along the lines of inheritance with Javascript. I’ve hidden lots of important details, but if you want to know more, ask or search for it. I should also note that my example doesn’t give you the power of protected fields. For example, Circle can’t directly access _x.

 

 

Advertisements

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

%d bloggers like this: