javascript - 如何在 Javascript 的子类中重载父类的方法?

标签 javascript oop inheritance

我正在尝试编写一个从父类扩展的 javascript 类,重载一个方法并稍微更改它。

例如,它检查一些变量,如果它们被设置为真,那么它在父级上执行相同的方法,否则它执行一些不同的代码。

这是我想出的:

function Dad(name)    
{
    this.yell = function()
    {
        console.log( 'GRRRRRRR ' + name);
    }
}

function Kid(name, age)    
{
    var parent = new Dad(name);


    parent.yell = function()
    {
        if (age < 15)
            console.log( 'BAAAAA ' + name );
        else
            parent.yell(); //This is the problem line, how to call this method on
                           //parent object
    }
    return parent;
}

var k = new Kid('bob', 13);
k.yell();

但问题是,如何调用父对象上的方法。

有什么想法吗?

最佳答案

使用原型(prototype)。它们允许您访问父类(super class)的方法,但无需对其进行实例化。

然后,从子类,你可以做 SuperClass.prototype.instanceMethod.call(this),这在大多数典型的 OO 语言中基本上是 super,但是 JS不能帮助您弄清楚父类(super class)是什么。所以你必须自己跟踪它。

// Superclass
function Dad() {};
Dad.prototype.yell = function() {
    console.log("Do your homework!");
}

// Subclass
function Kid(age) {
    // calls the constructor of the superclass.
    // in this case, the Dad() constructor does nothing, so it's not required here.
    Dad.call(this);

    // save constructor argument into this instance.
    this.age = age;
};

// Inheritance happens here, prototype is an instance of superclass
Kid.prototype = new Dad();

// Make sure the constructor is properly assigned.
Kid.prototype.constructor = Kid;

// Override an instance method.
Kid.prototype.yell = function() {
    if (this.age < 18) {
        console.log('Waaaaa, I hate homework');
    } else {
        // calls the yell method of the superclass
        Dad.prototype.yell.call(this);
    }
}

// make a kid.
var k = new Kid(13);
k.yell(); // 'Waaaaa, I hate homework' 

// make an old kid.
var k = new Kid(30);
k.yell(); // 'Do your homework!' 

JS 中的 OO 继承可能很困惑,但有一些方法可以提供帮助。

仅举几例。

关于javascript - 如何在 Javascript 的子类中重载父类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961032/

相关文章:

javascript - 如何强制 Web 浏览器单击页面上的链接?

javascript - 当我发布表单时,提交表单时无法调用 null 的方法 "submit "

javascript - TD :nth-of-type ('+element+' ) not working in casperjs

c++ - 多态性和私有(private)数据成员

c++ - 方法定义需要使用类的私有(private)声明

javascript - obj.prototype = new ParentObj(); 之后的对象方法消失了在 JavaScript 中

javascript - Nightmare JS 不工作

Javascript mixin 模式设置实例特定的 this 变量

c++ - 当我收到 `slicing` 的案例时?

java - Xml 架构接口(interface)