2013-03-04 87 views
0

我開始一個項目,我將主要開發Web應用程序的前端GUI,並決定使用MooTools而不是jQuery,因爲它具有更好的OOP功能。然而,在測試時,我作爲Java開發人員遇到了一些奇怪的事情。這裏的問題是:MooTools:父對象調用子方法

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! 

現在我有點困惑在這裏...不應該最後一行寫着「從父!」?

回答

3

不,這就是多態性應該如何工作。即使您正在調用Parent類中定義的方法,您仍然處於子項實例中,因此將調用Child中的重寫方法。

+1

OP:同樣,你不是在擴展父項,而是在通過Implements進行混合。這將不允許你執行'.parent()'調用 – 2013-03-04 14:07:22

+1

嘗試'Extends:Parent',然後在show中,你可以這樣做:'this.parent();'調用父級proto。 – 2013-03-04 14:21:18