父对象调用子方法

MooTools: Parent object calls child method

本文关键字:子方法 调用 对象      更新时间:2023-09-26

我正在启动一个项目,我将主要为web应用程序开发前端GUI,并决定使用MooTools而不是jQuery,因为它具有更好的面向对象功能。然而,在测试过程中,从我作为Java开发人员的角度来看,我遇到了一些奇怪的事情。问题在这里:

var Parent = new Class({
    initialize: function() {
        console.log("Parent constructor call!");
    },
    show: function() {
        console.log("From Parent!");
    },
    someParentMethod: function() {
        console.log("Some parent method");
        this.show();
    }
});
var Child = new Class({
    Implements: Parent,
    initialize: function() {
        console.log("Child constructor call!");
    },
    show: function() {
        console.log("From Child!");
    },
    display: function() {
        this.show();
        this.someParentMethod();
    }
});
var c = new Child();
c.display();

它的输出是:

Parent constructor call!
Child constructor call!
From Child!
Some parent method
From Child!

现在我有点困惑了…最后一行不应该是"来自父母!"吗?

不,这就是多态性应该如何工作的。即使调用在Parent类中定义的方法,您仍然处于Child 实例中,因此调用Child中被覆盖的方法。