在javascript中覆盖内部函数的行为

时间:2017-01-25 09:51:16

标签: javascript method-overriding

我想在javascript中覆盖内部函数。这是代码:

function Menu(x, y, z) {    
  this.createMenu = function(x, y) {
    //Some functionality
  }    
}

我想覆盖createMenu函数而不覆盖完整的Menu函数。有没有办法这样做。

2 个答案:

答案 0 :(得分:2)

您可以在其实例中覆盖它。

//span[text()='Save']/ancestor-or-self::button

答案 1 :(得分:0)

有两种可能的方法,一种是覆盖和覆盖 原始构造函数和引入工厂的构造函数 创建构造函数的实例,并重新分配新行为 已经存在的财产。

采用后一种方法,一个是健全且安全的,但需要控制 将所有代码出现次数new Menu( ... )更改为例如createModifiedMenu

只有当一个人不想或根本不能改变那些提到的那些时 代码出现,并且仅在某种类型的检查不依赖于操作时 使用instanceof,应考虑采用前一种方法......

"覆盖和包装"方法......

//
//  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);

工厂方法......

//
//  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( ... )`