0

I'm working on my own model layer in a node app. We have a ModelBase class that all of our Models inherit from. This works great. What I'd now like to do is make Models be able to inherit from other Models so that they also inherit their schemas and prototype methods.

I have 99% of this working, with the exception of extending schemas. I'm hoping someone can help me figure out an elegant solution for this. I'd like to not pass in the schema to the model constructors.

Here's a basic example which shows a sample ModelBase, ModelA, and ModelB.

I want ModelB's schema to extend ModelA's schema. Help with this would be greatly appreciated.

var util = require('util');

// BASE MODEL
var ModelBase = function(schema) {
  this.schema = schema;
};

ModelBase.prototype.baseMethod = function() {
  return console.log('base method');
};

// MODEL A inherits from MODEL B
var SCHEMA_A = { a: 'foo' };

var ModelA = function() {
  ModelBase.call(this, SCHEMA_A);
};

util.inherits(ModelA, ModelBase);

ModelA.prototype.test = function() {
  return console.log('test');
};

ModelA.prototype.foo = function() {
  return console.log('foo');
};

// MODEL B inherits from MODEL A
var SCHEMA_B = { b: 'foo' };

var ModelB = function() {
  ModelA.call(this, SCHEMA_B);
};

util.inherits(ModelB, ModelA);

ModelB.prototype.test = function() {
  return console.log('test B');
};

//
var mdlA = new ModelA();
var mdlB = new ModelB();

console.log( mdlA instanceof ModelBase ); // true
console.log( mdlB instanceof ModelA ); // true

// mdlA.test(); // test
// mdlB.test(); // test
// mdlB.foo(); // foo

console.log( mdlA.schema ); // { a: 'foo' }
console.log( mdlB.schema ); // { a: 'foo' }, should also have { b: 'foo' }

I'm not really sure how to do this, but I've got a good handle on why it works the way it does. ModelB is is inheriting ModelA's prototype, which calls ModelBase with SCHEMA_A, losing SCHEMA_B. I'm not sure how to fix this.

Any ideas?

doremi
  • 14,921
  • 30
  • 93
  • 148

1 Answers1

0

You can do mix ins or multiple inheritance by copying the "Parents" prototype members on the "Child" but instanceOf will not be true anymore. Then you may need to run multiple initializers of the Parents. When ParentA and ParentB have the same method you have to decide if you want to stack them (for methods like getAvailableMethods) or overwrite them (last "inherited" overwrites previous one.

An example of a mix in can be found here.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160