Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add methods to class Node.js

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?

like image 553
John Smith Avatar asked Mar 19 '26 11:03

John Smith


1 Answers

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.

like image 90
Felix Kling Avatar answered Mar 22 '26 00:03

Felix Kling