Skip to content

Instantly share code, notes, and snippets.

@thefridge111
Created January 18, 2018 20:18
Show Gist options
  • Save thefridge111/6ea0675c3bf0cb0855c67290fe967764 to your computer and use it in GitHub Desktop.
Save thefridge111/6ea0675c3bf0cb0855c67290fe967764 to your computer and use it in GitHub Desktop.
Convenient method of creating objects in javascript so that you have 'safe' default values when you construct objects and that are easy to maintain. This method greatly reduced complexity in our app and allowed us to more easily model Java class behaviors. Hope this is useful for someone.
function SomeObject(data) {
var obj = this;
// Used as a generic setter where we arent doing any manipulation
function setter(value) {
return value;
}
function listSetter(values) {
var valueList = [];
for (val in values) {
valueList.push(values[val]);
}
return valueList;
}
var fieldNames = {
id: [null, setter], // Some number attr
time: [null, function(val) { return new Date(val); }], // Some Date attr
hidden: [false, setter], // Some boolean attr
subject: ['', setter], // Some string attr
fileName: ['', function(val) { return '../' + val + '.png'; }], // Some custom field attr that require additional work to initialize
objRef: [null, function(val) { return new SomeOtherObj(val); }], // Some attr that depends on another objects constructor
toRoles: [[], listSetter] // Some list attr
};
for (var field in fieldNames) {
// To reduce confusion when we call the setter function of each field
var curr = fieldNames[field];
if (data && !dcdUtil.nullUndefinedCheck(data[field])) {
obj[field] = curr[1](data[field]);
} else {
obj[field] = curr[0];
}
}
}
// If you needed to you can sort of group 'classes' together and still gain access to them through a base class
// I usually do this if I'm only going to really use some other JS 'class' with another object. So in this instance,
// I'd only use NestedObject in conjunction with SomeObject
SomeObject.NestedObject = function(data) {
var nest = this;
function setter(val) {
return val;
}
var fields = {
id: [null, setter],
stuff: ['', setter
};
for (var field in fields) {
// To reduce confusion when we call the setter function of each field
var curr = fields[field];
if (data && !dcdUtil.nullUndefinedCheck(data[field])) {
obj[field] = curr[1](data[field]);
} else {
obj[field] = curr[0];
}
}
}
@thefridge111
Copy link
Author

I've also used the same sort of method as NestedObject to attach some constant values to the prototype or some function etc. The sky is the limit on how you chain this stuff together but this illustrates a good base on how to approach this sort of thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment