【问题标题】:How to overload a parent's method in a child class in Javascript?如何在Javascript的子类中重载父类的方法?
【发布时间】:2012-12-19 20:56:06
【问题描述】:

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

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

这是我想出的:

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

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

有什么想法吗?

【问题讨论】:

  • 通常的做法是将yell方法存储在Dad.prototype中,以后可以安全地找到它。
  • 当你做parent.yell = ...时,存储在那个位置的原始函数会丢失,所以你需要提前将它存储在某个地方才能使用它。

标签: javascript oop inheritance


【解决方案1】:

使用原型。它们允许您访问超类的方法,但无需实例化它。

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

// 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 继承可能很混乱,但有一些东西可以提供帮助。

仅举几例。

【讨论】:

  • 我投票赞成添加一个额外的行 Kid.prototype.constructor = Kid 以帮助 Firefox 正确命名该对象。
  • 这有点糟糕,因为我必须更改超类的所有方法以使用原型而不是 this.function 语法。这会破坏任何使用超类的现有代码吗?
  • 另外,在父函数中定义了很多私有变量,例如function Dad() { var privVar, privVar2}等。如果我切换到原型语法,所有这些都会丢失吗?
  • 很难用原型维护私有范围的变量。但是在进行继承时不使用原型要困难得多。通常,“私有”变量存储为带有下划线前缀this._age = agethis 的属性。这并不是真正的私密,但只有在真正关注安全性时才重要。
  • 在这种情况下,如果不破坏很多向后兼容性,我就不能使用这种方法,但是将来我会取消私有变量并改用this.var
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2012-08-04
  • 2013-10-13
  • 1970-01-01
相关资源
最近更新 更多