网络编程
位置:首页>> 网络编程>> JavaScript>> Mootools 1.2教程(21)——类(二)(2)

Mootools 1.2教程(21)——类(二)(2)

作者:Fdream 来源:Fdream博客 发布时间:2008-12-28 20:58:00 

标签:mootools,类,javascript,ajax,教程


Extends(扩展)

如果你想要覆盖基类中定义的方法和变量,你可以使用Extends。简单地把上面代码中的“Implements”替换成“Extends”就可以了。

参考代码: 

var ExtendingClass = new Class({ 
    // 注意这里用Extends替代了Implements 
    Extends : BaseClass, 
    // 下面的这些都在BaseClass中定义了 
    // 但是我们用extend替代了implements 
    // 这将覆盖在BaseClass中的定义 
    definedVariable : "Defined in ImplementingClass", 
    testFunction : function(){ 
        alert('This function is also defined in BaseClass'); 
    } 
}); 

var demo_four = function(){ 
    // 创建一个ImplementingClass实例 
    var test_class = new ExtendingClass('this is the input value'); 

    // 调用testFunction()(同时在BaseClass和ExtendingClass中都有定义) 
    test_class.testFunction(); 

    // 显示变量definedVariable的值(同时在BaseClass和ExtendingClass中都有定义) 
    alert('test_class.definedVariable : ' + test_class.definedVariable); 
}


使用extends的另外一个有用的功能是,它提供了一个功能:在覆盖基类的初始化方法时,你仍然可以调用基类中的初始化方法。因此,如果你在基类中定义了一个这样的初始化方法:

参考代码: 

initialize : function(){ 
    alert('base class'); 



然后,在扩展类中定义了下面这样一个初始化方法,那么将会弹出两个提示分别显示“base class”和“extending class”。

参考代码: 

initialize : function(){ 
    // 调用父类的构造函数 
    this.parent(); 
    alert('extending class'); 


如果父类的初始化函数需要参数,请一定要确保在这个初始化函数中又相同的输入参数并传递给父类的构造函数。在下面的示例中,请注意我们没有给input指定任何值——我们只是把它传递给了父类的构造函数,它会自动管理好的。

参考代码: 

var ExtendingClass = new Class({ 
    // 重复一遍:我们在使用扩展方法,而不是实现 
    Extends : BaseClass, 
    initialize: function(input){ 
        // 通过调用this.parent来执行父类的初始化方法 
        this.parent(input); 
        // 这样我们可以在初始化方法中做一些其他的事情 
        // 而不用完全覆盖父类的方法 
        this.otherVariable = "Original Input Was : " + input; 
    } 
}); 

var demo_five = function(){ 
    // 创建我们的扩展类实例 
    var test_class = new ExtendingClass('this is the input value');     

    // 调用testFunction 
    test_class.testFunction(); 

    // 显示变量otherVariable的值 
    alert("test_class.otherVariable : " + test_class.otherVariable); 
}

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com