mootools延伸课程

时间:2012-05-25 15:01:00

标签: javascript oop mootools

我有这段代码:

var MyClass = new Class({
    Implements: [Options,Events],
    initialize: function(){

    },
    doStuff: function() {
        console.log('In MyClass');
    }
});


var MyBetterClass = new Class({
    Extends: MyClass,
    initialize: function() {

    },
    doExtraStuff: function() {
        console.log('In MyBetterClass');
    }        
});    

var a = new MyBetterClass();

当某个地方调用doStuff时,我也希望调用doExtraStuff。我该怎么做呢?所以我不必乱用别人的代码,但是当他们的代码中发生了某些事情时,我希望在我的代码中发生其他事情。父类中没有触发事件。

2 个答案:

答案 0 :(得分:3)

您不能在父类中调用子类方法。您可以覆盖父类的doStuff方法,通过子类的parent属性调用父方法,然后实现自己的代码。

超级

var MyClass = new Class({
    Implements: [Options,Events],
    initialize: function(){

    },
    doStuff: function() {
        console.log('In MyClass');
    }
});

子类

var MyBetterClass = new Class({
    Extends: MyClass,
    initialize: function() {

    },
    doStuff: function() {
        this.parent();
        console.log('In MyBetterClass');
        // your own implementation of this method
    }        
}); 

然后

var a = new MyBetterClass();
a.doStuff(); // prints on console "In MyClass" and "In MyBetterClass"

答案 1 :(得分:2)

你应该做的是覆盖MyBetterClass中的doStuff方法,然后在超类上调用重写方法:

var MyClass = new Class({
    Implements: [Options,Events],
    initialize: function(){

    },
    doStuff: function() {
        console.log('In MyClass');
    }
});


var MyBetterClass = new Class({
    Extends: MyClass,
    initialize: function() {

    },
    doStuff: function() {
        this.parent();
        console.log('In MyBetterClass');
    }        
});    

var a = new MyBetterClass();