I have been fiddling around with object building via composition in Javascript (specifically NodeJS) and I have come up with a way of building up my objects but I need to know if this is an insane way of doing things.
The simple version is this: I have two objects, both have two properties, one holding a number and the other holding a string.
File: Cat.js
function Cat() {
this.name = 'Fuzzy Whiskerkins';
this.owner = 'James';
}
module.exports = Cat;
File: Car.js
function Car() {
this.color = 'blue';
this.owner = 'James';
}
module.exports = Car;
I would like to now add a basic getter/setter function for all properties in both of these objects. I would also like to be able to check that the value passed into these setters matches the type. Instead of writing four prototype functions for each of these properties I have done the following:
File: StringProperty.js
module.exports = function(newObject, propertyName) {
newObject.prototype[propertyName] = function( newString ) {
if ( typeof newString !== 'undefined' ) {
if ( typeof newString !== 'string' ) {
return;
}
this.properties.[propertyName] = newString;
return this;
}
return this.properties.[propertyName];
}
}
File: Cat.js
var StringProperty = require('./StringProperty.js');
function Cat() {
this.properties.name = 'Fuzzy Whiskerkins';
this.properties.owner = 'James';
}
StringProperty( Cat, 'name' );
StringProperty( Cat, 'owner' );
module.exports = Cat;
File: Car.js
var StringProperty = require('./StringProperty.js');
function Car() {
this.properties.color = 'blue';
this.properties.owner = 'James';
}
StringProperty( Car, 'color' );
NumberProperty( Car, 'owner' );
module.exports = Car;
Now both objects have all the basic functionality they need and I was able to do it with a minimal amount of code and whenever I need to add another string property the amount of code I will have to add will be minimal.
Am I crazy? Is this an insane thing to/is there a better way to be doing this?
EDIT: What I am trying to accomplish with this is the application I am working on has 100+ objects and each with 10+ properties and the idea of having to write almost the exact same code for every single one of those properties does not set well with me. I would prefer to be able to have a bit of code that adds the property and creates the getter/setter functions (with adding options for divergence in property restrictions such as different length restrictions on string properties). I have looked at multiple examples of object construction via composition in JS but nothing I tried fit into the NodeJS module structure.