Click here to Skip to main content
Click here to Skip to main content

jOOPL: object-oriented programming for JavaScript

By , 30 Jan 2013
 

Introduction

Web development has increased its complexity during the last decade. Think about how the Web was and in what it turned now: the Web of applications. Also known as Web 2.0 and the coming 3.0.

JavaScript has been the language that accompanied the Web since its early stages. Someday was the way to add some fancy effects to our pages, but as the language has evolved into an actual application programming language, the need to reuse and scale have become an important point in Web development.

Definitively, object-oriented approach on graphical user interface, domain and others, has demonstrated that is a good way of creating well-structured, reusable and maintainable software.

The worst part is JavaScript is not an object-oriented programming language: it is prototype-oriented, which is a weak approach to leverage few features of a full-fledged object-oriented platform.

That is why jOOPL exists (Official Site on Codeplex). "jOOPL" stands for "JavaScript Object-Oriented Programming Library". It is just that: a light-weight, easy-to-use and just object-oriented programming library allowing pure JavaScript to leverage more advanced features like:

  • Inheritance. 
  • Polymorphism. 
  • Encapsulation. 
  • Composition. 

And just that. jOOPL is not doing tasks like:

  • DOM manipulation.
  • DOM event handling.
  • AJAX

Finally, jOOPL is fully-open source and it is licensed under Apache v2 license.

Using the code

Let's create a very simple sample showing the power of object-oriented programming using jOOPL on plain and standard JavaScript.

Think about the very common sample about two-dimensional polygons: triangles, squares, pentagons... All of them are just polygons and those have different formulas to calculate their area. That is, it should be a class called Polygon with a polymorphic method to calculate the whole area:

// First of all, we are going to declare a namespace for the class
$namespace.register("Joopl.Samples");

// Next part will be about designing the whole class
Joopl.Samples.Polygon = $class.declare(
// The constructor
function() {
    // This is very recommended: if you declare a class field in the constructor,
    // it will hold a default value instead of undefined
    this.$_.args = null;
},
{
  // Sets an object that will hold the arguments to calculate the polygon's area
  set_Args: function(value) {
    this.$_.args = value;
  },
  
  // Gets an object that will hold the arguments to calculate the polygon's area
  get_Args: function() {
    return this.$_.args;
  },
  
  // The method to calculate the area. Check that its body does implement nothing.
  // Derived classes will be the ones responsible of providing the formula to make the calculation.
  CalculateArea: function() {
  }
}
);

$namespace,$class... But, what is that? In jOOPL there are some reserved keywords. Any of them start with dollar sign ($). Some of them will be shortcut functions or full objects.

In our case, $namespace and $class are keywords that hold an object to manage both kind of entities (namespaces and classes) within JavaScript code.

Any code file should register itself the namespace that belongs to. If the namespace was declared before, jOOPL will just skip the namespace registration. Namespaces are child objects of the top-most one on JavaScript Web browser-based scripts: the Window object.

Actually, classes can be declared and stored in regular variables, but jOOPL encourages to do not do so in order to avoid naming collisions. 

About class declaration, $class keyword holds a class management object and, in this case, we are using the declare method. This can take these arguments (in order):

  1. classConstructor (mandatory) A function representing the constructor of the class. jOOPL does not support more than a constructor per class
  2. methods (mandatory) An object map of functions representing the class methods or behaviors
  3. baseClass (optional) A base clase to inherit. jOOPL does not support multi-inheritance.
  4. interfaces (optional) One or more interfaces that the class must implement

Implementing polygons...

Now let's say we want to implement Rectangle polygon. In order to properly implement it we need: 

  1. The measures of the rectangle (x, y)
  2. An override of CalculateArea in order to implement the Rectangle-specific calculation of its area
$namespace.register("Joopl.Samples");
  
Joopl.Samples.Rectangle = $class.declare(
function() { },
{
    CalculateArea: function() {
        if(this.get_Args() && this.get_Args().x && this.get_Args().y) {
          return this.get_Args().x * this.get_Args().y;
        }
        else {
          throw Error("Please give X and Y!");
        }
    }
},
Joopl.Samples.Polygon
);

// Using the $new keyword and shortcut function, we instantiate
// a rectangle and later we set the arguments to calculate the area
var someRectangle = $new(Joopl.Samples.Rectangle);
someRectangle.set_Args({ x: 10, y: 20 });

// This calls the whole method and calculates the area. For now,
// nothing will be shown in the document: it is just getting the result.
var result = someRectangle.CalculateArea();

Above code does not prove polymorphism at all (but it does for inheritance). Now let's imagine that we add a new method in the base class called OutputArea that writes to the document the result of calculating some polygon's area:

$namespace.register("Joopl.Samples");
  
Joopl.Samples.Polygon = $class.declare(
function() {
    this.$_.args = null;
},
{
  set_Args: function(value) {
    this.$_.args = value;
  },
  
  get_Args: function() {
    return this.$_.args;
  },
  
  CalculateArea: function() {
  },
  
  // This is the new method. It calculates the area and writes the result into the document! 
  OutputArea: function() {
    document.write(this.$_.$derived.CalculateArea());
  }
}
);

// Using the $new keyword and shortcut function, we instantiate a rectangle
// and later we set the arguments to calculate the area again!
var someRectangle = $new(Joopl.Samples.Rectangle);
someRectangle.set_Args({ x: 10, y: 20 });
  
// This calls the whole method and calculates the area and finally writes the result to the document.
someRectangle.OutputArea();

The OutputArea writes the result of calling the more specialized version of CalculateArea method.

As above code shows, jOOPL provides the reserved and built-in this.$_.$derived field in order to give access to the derived class' members. Accessing the method as part of the base class (i.e., this.CalculateArea()) is still valid, but it's calling the enclosing class version. 

Check this example in real-time on jsFiddle (follow the link). 

Final words 

This is a small sample of jOOPL potential. jOOPL supports almost every feature of object-oriented programming and it gives to JavaScript its great benefits.

Because it does not use any Web browser feature - just plain JavaScript -, jOOPL may work in any JavaScript interpreter or compiler, meaning that jOOPL is a platform-agnostic solution for object-oriented programming on JavaScript!

If you want to learn more about its features and find out how to leverage it, please visit the official jOOPL site on CodePlex http://joopl.codeplex.com 

Collaboration and feedback will be also appreciated.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

About the Author

Matías Fidemraizer
Software Developer (Senior)
Spain Spain
Member
Matías Fidemraizer is a professional with competence in software project management, architecture and development.
 
Young, having vocation in software, he's primarily self-taught and he has acquired more than 5 years of strictly R&D and innovation in a variety of scopes and businesses.
 
Being a quality lover, he develops stable, easily scalable and solid technical solutions, which is a direct consequence of introducing industry de facto standards in production processes, without losing the chance of working best with things that covered previous successful projects.
 
Mainly, his projects have been in Microsoft environments, basically focusing them in the development of state-of-the-art solutions using well-known technologies like .NET Framework, ASP.NET, SharePoint, SQL Server, C# and Visual Studio, also taking most-popular open source products, like NHibernate, Castle Windsor, Ninject or Enterprise Library, and more.
 
His main focus have been Web technologies since their early stages, either as regular user and software developer, taking advantage of Microsoft environments, he's a Web, software as a service (SaaS) and cloud computing specialist.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHmm...mvpFlorian Rappl31 Jan '13 - 14:08 
Usually I am a little bit more enthusiastic about something like this. In fact JavaScript is already object oriented (its a dynamic object-oriented scripting language). What you want to achieve here is inheritance as in class-based programming languages (JS is prototype based, which results in a different pattern). I actually implemented on my own some time ago, however, my idea wasn't new at that time either. Libraries like prototype are using such techniques since years.
 
If you read my article on the Mario5 game you will actually see "my" pattern in work. It does not have namespaces, but namespaces are just objects in JS. There is really nothing special about it. That being said: I do not see the main problem in "another implementation of an old idea", but in a comparison with different (probably more performance and comfort guided) ways of doing it (TypeScript, CoffeeScript). I do not doubt that your implementation is probably more sophisticated (or more complete) than mine, but I do not see the advantage of using another library to solve an old problem.
 
Bottom line: Are there any advantages (besides no need for a transpiler) of using your library instead of let's say TypeScript?
AnswerRe: Hmm... [modified]memberMatías Fidemraizer31 Jan '13 - 19:48 
First of all, thank you for your feedback.
 
Florian Rappl wrote:
Bottom line: Are there any advantages (besides no need for a transpiler) of using your library instead of let's say TypeScript?

 
Advantages:
 
- You get more than inheritance: true polymorphism. Using prototypes "as is" you can reuse an identifier. With jOOPL, either you can call a base method or base's constructor. And, in addition, you get formal inheritance too.
- jOOPL is actual, pure and plain JavaScript. It extends the language using the whole language.
- There're other libraries doing some kind of OOP, but those do other things: AJAX, DOM, events, ... For example: I need OOP capabilities. I could use jQuery or any other for that, but I don't need DOM. jQuery is a GREAT and impressive library, I love it, but it's too heavy for just OOP. jOOPL is a 2KB library and it does the very specific task of giving OOP features to JavaScript. And just this.
- You don't need tooling. You can develop jOOPL classes using Notepad, Visual Studio, Eclipse... And the code you develop is the one that's executed "as is". You don't need any additional thing to share your code with others.
- As far as I know, since jOOPL is implemented on top of plain JavaScript and it's not a translator like TypeScript, jOOPL-based code looks OOP while something like TypeScript and Dart output prototypes in a plain old JavaScript way. If I need to choose if I want to maintain the pure JavaScript code of jOOPL or just old prototypes, I find far way more readable jOOPL than prototypes (jOOPL uses prototypes behind the scenes, I know, but I'm talking about the surface or the higher level).
- TypeScript developers aren't JavaScript ones. I mean that jOOPL enforces the competences of regular JavaScript developers: you do things as you did before but using OOP. Just think if you want to be a JavaScript developer or "a developer targeting JavaScript who doesn't use JavaScript". After a while, you're going to be agnostic to actual JavaScript language. Do you imagine someone asking you "do you want to collaborate with us?" and you ask "are you using TypeScript?", and they tell you "no, we use plain JavaScript". Are you going to be able to do the same things as TypeScript using pure JavaScript without any library and in time? I doubt it. This isn't the case of jOOPL, because code with and without jOOPL can co-exist and you just need a 2KB dependency!
 
For me, the main advantage of using TypeScript (or Dart, or any other) is that, during development stages, you get "a more like C# or Java" development feel: it's like coding strongly-typed JavaScript and it still compiles into regular JavaScript. But TypeScript isn't ECMA-Script, is it? At the end of the day, these kind of solutions are a "lock-in" into some vendor environment.
 
Perhaps I would make myself the next question: if I need to develop JavaScript, do I need to learn another language to just use JavaScript?
 
Each environment, framework and languages have it's pros and cons and I prefer to work with them rather than creating a translator in order to have what I would love to get in my favorite language.
 
I hope I could convince you or, at least, you found me reasonable Smile | :)

modified 1 Feb '13 - 2:19.

GeneralRe: Hmm...mvpFlorian Rappl31 Jan '13 - 21:47 
I understand your points, but you are missing some things (in my opinion):
 
- It does not matter if I need your library or TypeScript - both are dependencies.
- TypeScript is NOT a new language - it is a true superset of JavaScript (or lets say ECMAScript), i.e. every current *.js file will run just fine with TypeScript.
- TypeScript offers more with OPTIONAL strong types. That's a feature no one can deny.
- It does not matter if I learn the "keywords" (well, obviously they are just objects / functions, but still - some names) of your library or of TypeScript. Therefore the effort required to fully utilize the new possibilities is equivalent.
- TypeScript is actually quite close to ECMAScript 6 - in fact: that was one of the design goals. Once ECMAScript 6 is supported everywhere, you will benefit from the performance boost, since less scripting operations will be required for your script(s) to use constructs like classes and such.
 
As I said: I wrote my own framework for that (it's a small file with like 25 lines). I could do inheritance, automatic class construction, static properties and methods and more. However, since TypeScript has been released I do not see any reason why I should continue on following that path.
 
That being said: I still think your article is great, I just wanted to point out that there might be better options if one considers a transpiler.
GeneralRe: Hmm...memberMatías Fidemraizer1 Feb '13 - 0:14 
Hi and thanks again for your feedback!
 
I'm going to answer you point by point:
 
Florian Rappl wrote:
- It does not matter if I need your library or TypeScript - both are dependencies.

Right. But one is a plain JavaScript library and it's just about adding the dependency to have its benefits versus TypeScript: your code requires a "compiler".
 
Even if its a superset of JavaScript, TypeScript needs compilation to work in any JavaScript environment.
 
Conclusion: it's not the same a compiler dependency than a library dependency. Second is easier to replace. Try to replace a non-existent JavaScript
 
Florian Rappl wrote:
TypeScript offers more with OPTIONAL strong types. That's a feature no one can deny.

It would be wrong to discuss the benefits of a language-level OOP implementation. In both cases (TypeScript or jOOPL approach) the benefit is artifical, but in the case of TypeScript, it's a design-time feature rather than a run-time one. TypeScript generates regular prototypes and less readable JavaScript (I mean the "transpiled" one!). In my case - and this is my point of view -, I don't want to degradate JavaScript and convert it to an intermediate language.
 
Florian Rappl wrote:
- It does not matter if I learn the "keywords" (well, obviously they are just objects / functions, but still - some names) of your library or of TypeScript. Therefore the effort required to fully utilize the new possibilities is equivalent.

I'm absolutely agree: you've a learning curve and specific knowledge that may be useless if you can't use jOOPL.
 
Which isn't equivalent is the approach: one forces you to learn some "keywords" that work on any JavaScript interpreter/compiler today, and the other forces you to learn a "superset of JavaScript" that may or may not run on current Web browsers and JavaScript platforms. At least, I feel that using jOOPL gives me some advantage in this area: I use OOP on current standard and widely-used JavaScript version without a "transpiler".
 
As I said in the other reply, don't you find this a good point? What if Microsoft decides that TypeScript shouldn't be released (it's still a preview). They're a company and they work for business. I don't find it a wrong behavior, but it can compromise my projects.
 
Right I'm the author of jOOPL, but I prefer to stick with it because it's not a vendor lock-in. Ok, it's a "dependency lock-in", but this is software and we do it using the collective effort of everyone (I use many open source libraries) and I prefer to get "locked" by something that works with the real-world JavaScript rather than something that's "I would like to have this as core language features and I get agnostic to a Microsoft, Google or any other interpretation of how JavaScript should be".
 
If some day we get ECMA-Script6 and it incorporates true OOP to the JavaScript language, you know my answer: I'll go for it!!!
 
At the end of the day, it's like the decision of using or not using LESS. But, AFAIK, in the case of LESS there's no upcoming standard that would fit the void of not using LESS.
 
Florian Rappl wrote:
That being said: I still think your article is great, I just wanted to point out that there might be better options if one considers a transpiler.

You're right, both a pure JavaScript library an a transpiler are different approaches to solve similar problems. Also both have their pros and cons and, depending on project and tech requirements, you're going to do the right choice Smile | :)
 
Thank you for the positive feedback. Don't think I dislike being criticized. I like it and I know that your points will be shared by a lot of developers.
QuestionjQuery compatibilitymemberSpiff Dog31 Jan '13 - 7:08 
How well does this mesh with jQuery, specifically since it also uses the "$"?
-------------------------
Spiffdog Design
It's ok... he doesn't bite...

AnswerRe: jQuery compatibilitymemberMatías Fidemraizer31 Jan '13 - 8:48 
Hi!
 
No problem with jQuery as, in the case of jOOPL, the dollar sign is a variable prefix rather than a function or object shortcut.
 
In jOOPL there's no
$.
. It has keywords like $new, $namespace, $class which are regular JavaScript variables.
 
Thank you for asking it, your question should clarify a lot of things to other visitors Smile | :)
GeneralRe: jQuery compatibilitymemberSpiff Dog31 Jan '13 - 13:01 
Oh good! Thanks for clarifying. I'll give this a go and see how it works.
 
Thanks again!
-------------------------
Spiffdog Design
It's ok... he doesn't bite...

GeneralRe: jQuery compatibilitymemberMatías Fidemraizer31 Jan '13 - 19:54 
No problem, it has been a pleasure.
 
If you want and you've questions while trying it, you can ask me in the official site for jOOPL on Codeplex http://joopl.codeplex.com opening a discussion thread or an issue in the issue tracker.
 
Thank you for trying it! Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 30 Jan 2013
Article Copyright 2013 by Matías Fidemraizer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid