覆盖基类函数 [英] Override a base class function

查看:115
本文介绍了覆盖基类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我迫切需要子类来覆盖基类特权函数。我不确定这是否可行,但如果有人可以告诉我它是否是&怎么做。如果它不可能,还有另一种方法来实现我在下面的简单代码示例中尝试做的事情吗?

In Javascript I have a desperate need for a child class to override a base classes privileged function. I am unsure if this is possible to do, but it would be great if someone could tell me if it is & how to do it. If its not possible, is there another way to acheive what I am trying to do in the simple code example below?

我无法转换基类函数parseXML( )公开,因为它需要访问私有变量

    function BaseClass()
    {
        var map = {};

        // I cannot make this function public BECAUSE it accesses & changes private variables
        this.parseXML = function( key, value )
        {
            alert("BaseClass::parseXML()");
            map[key] = value;
        }
    }

    function ChildClass()
    {
        BaseClass.call(this);
        this.parseXML = function( key, value, otherData )
        {
            alert("ChildClass()::parseXML()");

            // How can I call the base class function parseXML()?
            //this.parseXML();  // calls this function not the parent function
            //MyClass.prototype.doStuff.call
            BaseClass.prototype.parseXML.call(this, key, value);  // fails
            //BaseClass.prototype.parseXML(); // fails

            // perform specialised actions here with otherData
        }
    }

    ChildClass.prototype = new BaseClass;

    var a = new ChildClass();
    a.parseXML();


推荐答案

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

实例

基本上,您缓存特权方法(仅在对象上定义),然后在分配给特权的新函数内调用它方法名称。

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

实例

另外奖金使用 pd 实施

这篇关于覆盖基类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆