There are two possible approaches, one that wrappes and overwrites
the original constructor and one that introduces a factory which does
create an instance of the constructor and also does reassign new behavior
to an already existing property.
With the latter approach one is sound and safe but needs to be in control
of changing all code occurrences of new Menu( ... ) to e.g createModifiedMenu.
Only if one does not want to or is not at all able to change those mentioned
code occurrences and only if one's type checking does not depend on operating
with instanceof one should consider going with the former approach ...
"overwriting and wrapping" approach ...
//
// closed implementation of code one does not own.
//
function Menu(x, y, z) {
this.createMenu = function(x, y) {
//Some functionality
}
}
//
// "overwriting and wrapping" approach.
//
Menu = (function (proceed) {
function alternativeCreateMenu(x, y) {
// alternative createMenu implementation
}
function ModifiedMenu(/*x, y, z*/) {
// "restoration fake" of the original constructor.
this.constructor = proceed;
// super call via original constructor.
proceed.apply(this, arguments);
// altering the behavior.
this.createMenu = alternativeCreateMenu;
}
// finsihing the inheritance step.
ModifiedMenu.prototype = (new proceed);
return ModifiedMenu;
}(Menu));
var menu = new Menu("a", "b", "c"); // ... thus, no instantiation shipped with
// already existing code needs to be touched.
console.log("menu : ", menu);
factory approach ...
//
// closed implementation of code one does not own.
//
function Menu(x, y, z) {
this.createMenu = function(x, y) {
//Some functionality
}
}
//
// factory approach.
//
var createModifiedMenu = (function (Menu) {
function alternativeCreateMenu(x, y) {
// alternative createMenu implementation
}
return function (x, y, z) { // factory.
var
menu = new Menu(x, y, z);
menu.createMenu = alternativeCreateMenu;
return menu;
};
}(Menu));
var menu = createModifiedMenu("a", "b", "c"); // ... thus, every instantiation shipped with
// already existing code needs to be changed
console.log("menu : ", menu); // from `new Menu( ... )` to `createModifiedMenu( ... )`
createMenuisn't a property in it's own right, so cannot be directly access and overridden.