2

I am trying to achieve something like following in Node.js and Express.js, not able to find good examples of active this. Help appreciated.

base.js
--------
module.exports = {
  baseFunction: function(){
    .....
  }
}

child.js
--------
module.exports = {
  require('base'),

  ***** Some Magical Code ****** 

  childFunction: function(){
    ..... 
  }
}



CallProgram.js
--------------
var child = require('child');
child.baseFunction();    
4
  • What are you really trying to achieve? Incase you are not aware of module system of node refer itsallabtamil.blogspot.in/2012/01/… Commented Aug 30, 2012 at 12:31
  • I have few generic methods which i do not wish to repeat in 25 child modules. I was looking for something like require('base'); in child programs which will enable access to base methods without having to duplicating the code. I might override the code some child classes if required. Hope this makes sense. Commented Aug 30, 2012 at 13:12
  • crockford.com/javascript/inheritance.html Commented Aug 30, 2012 at 13:20
  • Whatever you are trying to do is correct but the way you are doing is wrong :) Commented Aug 30, 2012 at 14:37

2 Answers 2

2

How about this?

function extend(a, b) {
  var result = Object.create(a);
  for (var prop in b) {
    if (b.hasOwnProperty(prop)) {
      result[prop] = b[prop];
    }
  }
  return result;
}

module.exports = extend(require('base'), {
  ***** Some Magical Code ****** 

  childFunction: function(){
    ..... 
  }
});

The extend function will create a new object with a as its prototype and will copy all properties of b onto it.

Sign up to request clarification or add additional context in comments.

Comments

0

You can check ZinkyJS, It offers a very clean way to make routing inheritance

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.