Override privileged method of base class

前端 未结 2 913
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 09:17

How can I go about making a child class override a privileged method of a base class?

If its not possible, is there another way to achieve what I am trying to accomp

2条回答
  •  隐瞒了意图╮
    2020-12-25 09:26

    function BaseClass() {
        var map = {};
        this.parseXML = function(key, value) {
            alert("BaseClass::parseXML()");
            map[key] = value;
        }
    }
    
    function ChildClass() {
        BaseClass.call(this);
        var parseXML = this.parseXML;
        this.parseXML = function(key, value, otherData) {
            alert("ChildClass()::parseXML()");
            parseXML.call(this, key, value);
        }
    }
    
    ChildClass.prototype = new BaseClass;
    
    var a = new ChildClass();
    a.parseXML();
    

    Live Example

    Basically you cache the privileged method (which is only defined on the object) and then call it inside the new function you assign to the privileged method name.

    However a more elegant solution would be:

    function BaseClass() {
        this._map = {};
    };
    
    BaseClass.prototype.parseXML = function(key, value) {
        alert("BaseClass::parseXML()");
        this._map[key] = value;
    }
    
    function ChildClass() {
        BaseClass.call(this);
    }
    
    ChildClass.prototype = Object.create(BaseClass.prototype);
    ChildClass.prototype.parseXML = function(key, value, otherData) {
        alert("ChildClass()::parseXML()");
        BaseClass.prototype.parseXML.call(this, key, value);
    }
    
    var a = new ChildClass();
    a.parseXML();
    

    Live Example

    Also bonus implementation using pd

提交回复
热议问题