JavaScript objects My way

This is not a tutorial and I do not take full responsibility for the theory written here, this is just a post for myself, so that I don’t forget 🙂

You’ve probably worked with some OOP language in the past. You probably know how the typical syntax of OOP looks in any language (well in the most popular ones at least) . It looks something like this:

class MyClass {
  // The constructor
  public function MyClass(){

  }
  // Some private method
  private function _someFunction(){

  }
}

Well JavaScript is one kind of a different beast.

First of all – JS does not have a class keyword (it is a reserved keyword, but it is not used in the way we’ve used to). It’s all about anonymous functions and functions within functions OR objects.

There are three ways of doing objects in JS. I will talk about two of my favorite, but just to mention the third one involves the prototyping, which is really great feature, but I’m still not used to it, although you could also call it a late-extension mechanism, as with that approach you can extend existing objects. But we’re not going to cover this today.

Aproach Nº 1

A.k.a. static object with only public methods and members. A.k.a. a simple JS object. In ths approach you can use a simple JS object as shown here:

var MyObject1 = {
  _internalVar1 : 1,
  _internalVar2 : null,
  _internalFunction : function(){

  },
  externalFunction : function(){

  }
};

This basically creates an object with anonymous functions assigned to object keys. This also allows us to add some functions later on, or even overwrite some, but this does not give any sure control over function access rights (like private or protected) – every key is public, that means every method and variable is public and there is a chance to overwrite them as show here:

MyObject1.externalFunction = function(asdf){
  // This is now a different function
};

This approach is only good for cleaning up your code and grouping stuff together under certain “static classes” (let me call them like that).

Approach NÂş 2

A.k.a. functions within function (the Inception type of OOP 🙂 ). This is what used to spin my head around, as it’s not how I’m used to do it in PHP or Java. Let’s start with an example:

function MyClass1(arg1, arg2){
  var _privateVar1 = arg1;
  var _privateVar2 = arg2;
  var _privateMethod1 = function(){
    _privateVar1++;
  },
  _privateMethod2 = function(other_args){
    _privateMethod1();
    _privateVar2 = other_args;
  };
  return {
    publicMethod : _privateMethod2
  };
};

This approach allows you to write private members and methods. As you can test it yoursefl  _privateVar1 and _privateVar2 will not be available outside the function’s scope, neither they will be overwritable. Also _privateMethod1 and _privateMethod2 are available only from the function’s scope. Now the trick lays in the return value, which returns an object, that I’d like to call “public methods” or “exposed to public”. Now to some basics:

  • The constructor is the main function MyClass1 – it’s body creates all the private members and methods, it can receive arguments as a regular constructor
  • everything within the function stays within the function – so those are private members and private methods
  • return exposes public methods through an object wich allows us to do something like this:
  • var MyObject2 = MyClass1(1, 2);
    MyObject.publicMethod(5);

To create an immediate instance you can write something like this:

var MyObject3 = (function(){
  ... // internal code goes here
})()

This will create an anonymous function and execute it immediately returning public methods.  The trick is in the parenthesis after the function definition.

Now one more thing – this keyword. We’ve used to use this magic keyword to access object internal members and methods, but in JS this is totally unreliable in the case of OOP. In most cases it will always return window object, in the case of events it will return DOM object the event was dispatched from and it still depends how you define event callbacks. More on that here: http://www.quirksmode.org/js/this.html But to the rescue comes functions internal scope and some black magic as you can freely call any of the internal functions as is (also the internal scope has higher precedence when there is a method or a variable defined with the same name). Heck, you can even create sub-objects and all sub-objects will have access to the parent function private methods or members. Black magic I say. 🙂

PS. This is not a tutorial and I do not take full responsibility for the theory written here, this is just a post for myself, so that I don’t forget 🙂

Leave a Reply

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