Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / Javascript

jOOPL: Object-Oriented Programming for JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
20 Mar 2019Apache4 min read 30K   23   8
Discover a modern, solid, and powerful way of leveraging object-oriented programming on the Web and anywhere

Introduction

Web development has increased its complexity during the last decade. Think about how the Web was and in what it turned into 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:

JavaScript
// 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 for 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 it 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 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
JavaScript
$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();

The 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:

JavaScript
$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 the 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.

Collaboration and feedback will also be appreciated.

History

  • 30th January, 2013: Initial version

License

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


Written By
Software Developer (Senior)
Spain Spain
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.

Comments and Discussions

 
QuestionHmm... Pin
Florian Rappl31-Jan-13 14:08
professionalFlorian Rappl31-Jan-13 14:08 
AnswerRe: Hmm... Pin
Matías Fidemraizer31-Jan-13 19:48
Matías Fidemraizer31-Jan-13 19:48 
GeneralRe: Hmm... Pin
Florian Rappl31-Jan-13 21:47
professionalFlorian Rappl31-Jan-13 21:47 
GeneralRe: Hmm... Pin
Matías Fidemraizer1-Feb-13 0:14
Matías Fidemraizer1-Feb-13 0:14 
QuestionjQuery compatibility Pin
Spiff Dog31-Jan-13 7:08
Spiff Dog31-Jan-13 7:08 
AnswerRe: jQuery compatibility Pin
Matías Fidemraizer31-Jan-13 8:48
Matías Fidemraizer31-Jan-13 8:48 
GeneralRe: jQuery compatibility Pin
Spiff Dog31-Jan-13 13:01
Spiff Dog31-Jan-13 13:01 
GeneralRe: jQuery compatibility Pin
Matías Fidemraizer31-Jan-13 19:54
Matías Fidemraizer31-Jan-13 19:54 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.