I have three JavaScript objects. The first one serves merely as a prototype. The other two are implementation of a specific type.
var MainPrototype = {};
var SpecificType = $.extend(Object.create(MainPrototype));
var OtherSpecificType = $.extend(Object.create(MainPrototype));
I am missing the option of a parent
-method and am trying to implement some specifics for each specific type.
I started of by comparing the types within the main prototype object, yet I found the nesting if-else clausing worrysome and in case that new types would be introduced, I guess the code will get ugly fast. I also does not feel right to put the specifics into the main function.
var MainPrototype = {
function: bind() {
//generic stuff
if (this.type === SpecificType.type) {
// specifics for this type
} else if (this.type === OtherSpecificType.type) {
// specifics for other type
}
}
}
That's why I thought I could call a specific function dynamically.
var MainPrototype = {
bind: function() {
//generic stuff
var specificBindMethod = this.type + "Bind";
if (typeof(this[bindMethod]) === "function") {
this[categoryBindMethod]();
}
}
};
var SpecificType = $.extend(Object.create(MainPrototype, {
type: 'specific',
specificBind: function() {
// doSpecifics
}
});
var OtherSpecificType = $.extend(Object.create(MainPrototype, {
function: 'other',
otherBind: function() {
// doSpecifics
}
})
Now I can define the specific function within its proper object and only if they exist they will get called getting rid of the nesting.
I am wondering if this approach is better in terms of maintainability and extensibility or if I should have stayed with the if-else-approach or if there is anything better to solve my current use case.
bind
in the subclasses? You, as you say, implement specifics for the specific classes. Sometimes that means overriding the parents class' function \$\endgroup\$parent
method. I do not want to duplicate the generic parts, but keep that in the main object. If I would do this in another language I would do something on the lines ofSpecificObject.bind{ parent.bind(); doSpecificStuff() };
\$\endgroup\$super
available in all methods (CoffeeScript does this) \$\endgroup\$super
to access overridden methods. \$\endgroup\$