3

I have two classes, one Car:

var config = require('./configuration');

module.exports.Car = function(){}

module.exports.Car.prototype.set_tires = config.set_tires;
module.exports.Car.prototype.remove_tires = config.remove_tires; 

module.exports.Car.prototype.drive = function(){console.log("BRUMMM BRUMMM")}

and a Motorbike:

var config = require('./configuration');

module.exports.Motorbike = function(){}

module.exports.Motorbike.prototype.set_tires = config.set_tires;
module.exports.Motorbike.prototype.remove_tires = config.remove_tires; 

module.exports.Motorbike.prototype.drive = function(){ console.log("BR BR BRUUMM")}

As you see both implement methods from Configuration that looks like this:

module.exports.set_tires = function(tires){
    this.tires = tires;
}

module.exports.remove_tires = function(){
    console.log("The " + this.tires + " Tires will be removed");
    this.tires = null;
}

I wonder if there's another nicer way to implement the methods?? In this example I gave you there are only two shared methods, but with more you can easily lose the overview. Also I would like to know if there is a nicer way to not repeat module.exports to often?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
John Smith
  • 6,105
  • 16
  • 58
  • 109
  • 1
    Why do you not assign module.exports to a varible? Then you could spare yourself from writing module.exports again for each new method or property. – Blauharley Jun 20 '15 at 18:18

1 Answers1

2

It seems like you want to merge two objects. You can do this with Object.assign if available:

Object.assign(Motorbike.prototype, config);

See How can I merge properties of two JavaScript objects dynamically? for alternative ways.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Eh...not sure I'd recommend this if Firefox is the only one to have implemented it. Glad to see it's part of the standard though; libraries always implement this themselves. – Katana314 Jun 20 '15 at 18:38
  • I think I will go with that: https://www.npmjs.com/package/object-assign Thanks again! – John Smith Jun 20 '15 at 18:41
  • @Katana314: Given that we have polyfills, there is no reason not use new APIs. Transpilers even allow us to use new syntax and behavior. I believe it is on us to drive adoption here. – Felix Kling Jun 20 '15 at 18:42
  • @FelixKling Point taken. Also, I failed to notice this was specifically a NodeJS question (I answer lots of browser JS questions), so there's no issue there. – Katana314 Jun 20 '15 at 18:45