Click here to Skip to main content
15,891,607 members
Articles / Programming Languages / Javascript
Tip/Trick

Object Oriented Programming with DatumJs

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
6 Nov 2016MIT 9.2K   1  
Object Oriented Programming with DatumJs

Introduction

This is a lightweight library which enables object oriented programming with JavaScript.

Background

I was having trouble with implementing OOP concepts with JavaScript which led me to come up with a library which will enable OOP with native JavaScript. I hope you have heard there are two ways to implement OOP with JavaScript which are Classical model and Prototype model, unfortunately none of those gave me what it really means to have OOP.

Using the Code

Simply include datum.js in to your project. Check out the samples here.

Features

  • Support multi-level inheritance
  • Enables to access base class via this.base property

Methods

  • define: define a class
    JavaScript
    var Mobile = datum.define({
        //Meta data of the class
        __meta: {
            name: 'Mobile' // Name of the class
        },
    
        //properties
        manufacturer: '',
        operatingSystem: '',
        model: '',
        cost: '',
    
        //Constructor
        constructor: function (manufacturer, operatingSystem, model, cost) {
            this.manufacturer = manufacturer;
            this.operatingSystem = operatingSystem;
            this.model = model;
            this.cost = cost;
        },
    
        //Methods  
        getModel: function () {
            return this.model;
        },
        sendText: function(receiver, text){
            console.log('Text sent to ' + receiver);
        }
    });
  • create: Create an instance of a defined class
    JavaScript
    var mobile = datum.create(Mobile, "Nokia", "Win8", "Lumia", 10000);
  • clone: Clone an object
    JavaScript
    var mobileClone = datum.clone(mobile);

Inheritance

JavaScript
//Android
var Android = datum.define({
    //Meta data of the class
    __meta: {
        name: 'Android', // Name of the class
        extends: Mobile // Base class object
    },

    //Constructor
    constructor: function (manufacturer, operatingSystem, model, cost) {
        this.base(manufacturer, operatingSystem, model, cost);
    },

    //Methods
    getModel: function () {
        return "This is Android Mobile - " + this.model;
    }    
});

Browsers Support

  • Internet Explorer 8+
  • Firefox 3.1+
  • Safari 4+
  • Chrome 3+

License

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


Written By
Software Developer
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --