I am trying to understand JavaScript inheritance and I hit a road block. I am not familiar with JavaScript's prototype based inheritance. I am still using old NodeJS version so I can't use classes.
Could you tell me why following code prints the same values for different workers and how can I prevent it?
var Manager = require('./manager');
var worker1 = new Manager.getWorker('foo');
var worker2 = new Manager.getWorker('bar');
console.log(worker1.config);
console.log(worker2.config);
//Implementation Details
//Manager
(function() {
'use strict';
function Manager() {
}
Manager.getWorker = function(slug) {
var Worker = null;
try {
Worker = require('./workers/' + slug);
Worker = new Worker();
} catch (e) {
console.log('Worker error: cannot initiate worker');
}
return Worker;
};
module.exports = Manager;
})();
//foo.js
(function () {
var _abstract = require('../abstract_worker');
var _util = require('util');
var config = {
"slug": "foo",
"name": "Foo Worker"
};
function Foo() {
this.config = config;
Foo.super_.apply(this,arguments);
}
_util.inherits(Foo, _abstract);
module.exports = Foo;
})();
//bar.js
'use strict';
(function () {
var _abstract = require('../abstract_worker');
var _util = require('util');
var config = {
"slug": "bar",
"name": "Bar Worker"
};
function Bar() {
this.config = config;
Bar.super_.apply(this,arguments);
}
_util.inherits(Bar, _abstract);
module.exports = Bar;
})();
(function() {
'use strict';
//config
var _ = require('lodash');
var default_config = {
number_of_job: 1
};
function AbstractWorker() {
if (!this.config) {
this.config = {};
}
if (!_.isString(this.config.slug)) {
throw new Error('config.slug is undefined.');
}
if (!_.isString(this.config.name)) {
throw new Error('config.name is undefined.');
}
this.config = _.merge(default_config, this.config);
}
module.exports = AbstractWorker;
})();
EDIT: Thanks to @Bergi I found out the source of the error. It seems Lodash's merge
recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. In my code it seems I also made a typo and wrote in wrong order. I just leave it as it is maybe it can help others in the long run.