Es gibt zwei mögliche Ansätze, eine, die wrappes und den ursprünglichen Konstruktor und überschreibt, die eine Fabrik stellt die eine Instanz des Konstruktor schafft und auch neue Verhalten nicht neu zuweisen zu einer bereits bestehenden Immobilie.
Mit dem letzteren Ansatz ist solide und sicher, sondern muss die Kontrolle zu alle Code Vorkommen von new Menu(...)
ändern createModifiedMenu
z.
Nur wenn man nicht will oder ist überhaupt nicht alle in der Lage, diese erwähnten Code Ereignisse zu ändern, und nur, wenn man die Typprüfung nicht davon abhängt, mit instanceof
sollte man überlegen mit dem früheren Ansatz Betrieb gehen ...
"Überschreibung und Verpackung" -Ansatz ...
//
// 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);
Fabrik Ansatz ...
//
// 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(...)`
haben Sie etwas versucht? –
Nein, 'createMenu' ist keine eigene Eigenschaft, daher kann nicht direkt zugegriffen und überschrieben werden. –
Können Sie erwähnen, was Sie genau machen und warum? – sabithpocker