Inheritance - nodeGame/NDDB GitHub Wiki

It is easy to extend NDDB functionalities by inheritance. There are sevaral ways of doing it, and I will show here one.


// Requiring the NDDB prototype
var NDDB = require('./index.js').NDDB;

// Creating a copy of the NDDB prototype and assigning 
// it to the prototype of our class
ADB.prototype = new NDDB();
// Correctly specifying the the constructor (javascript 
// fails to do so)
ADB.prototype.constructor = ADB;

function ADB() {
    options = {};
    // Setting up my options
    NDDB.call(this, options);
    // other initialization
}

// Extending the ADB prototype (originally based on NDDB)
ADB.prototype.myNewMethod = function() { };

var adb = new ADB();

Specifying the constructor

Depending on how you specify the options inside the constructor, you can obtain slightly different behavior of the extended object. In particular, this affects views and hashes.

If hashes and views are specified after the call to original NDDB constructor, rather than as options in the configuration object, the order in which they are specified matters. In fact, the later defined views or hashes will include themselves all previously specified settings. If you want your views to include indexes and hashes then you need to follow the order specified in the following snippet.

function ADB() {
    NDDB.call(this);
    this.index('id', function(i) {
        return i.id;
    });
    this.hash('ha', function(i) {
        return i.id;
    });
    this.view('vi', function(i) {
        return i.id;
    });
}

Alternatively, if you specify your views and hashes in the configuration object passed to the NDDB contructor the order does not matter anymore, and all indexes and hashes are added to every view, and all indexes and views are added to every hashed dbs. See the following snippet:

function ADB() {
    options = {};
    
    options.I = {
        id: function(i) {
            return i.id;
        }
    };
    options.V = {
        vi: function(i) {
            return i.id;
        }
    };
    options.H = {
        ha: function(i) {
            return i.id;
        }
    };
    NDDB.call(this, options);
}