一起来学ASP.NET Ajax(三)之面向对象类型系统

来源:互联网 发布:nginx upupw 1.8.0 编辑:程序博客网 时间:2024/05/16 08:47

         我们知道JavaScript是一种基于prototype的面向对象脚本语言,其面向对象特性可以参见我的博客《JavaScript中的面向对象》,但是 JavaScript 本身不能作为面向对象的语言,因为它无法全面实现面向对象编程的三个支柱:继承、多态性和封装,虽然通过对象原型可以获得部分继承特性,通过闭包也可以获得部分封装特性。因此 Microsoft AJAX Library 会先为语言提供更多强大的工具,然后再继续定义新的类和编程工具。

        HTML代码:

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>面向对象系统</title></head><body>    <form id="form1" runat="server">    <asp:ScriptManager ID="ScriptManager1" runat="server">    </asp:ScriptManager>    <script language ="javascript" type="text/javascript">        //注册命名空间        Type.registerNamespace("AspNetAjaxOverView");        //空间下建立类        AspNetAjaxOverView.Person = function (firstName, lastName) {        //下划线开头表示私有            this._firstName = firstName;            this._lastName = lastName;        }        //修改person的prototype        AspNetAjaxOverView.Person.prototype =            {                 get_firstName: function () {                    return this._firstName;                },                get_lastName: function () {                    return this._lastName;                },                //覆写toString                toString: function () {                    return String.format("Hello,I am {0} {1}",this.get_firstName(), this.get_lastName());                }            }            //注册Person类            AspNetAjaxOverView.Person.registerClass("AspNetAjaxOverView.Person");                        //命名空间下添加employee类            AspNetAjaxOverView.Employee = function (firstName, lastName, title) {                AspNetAjaxOverView.Employee.initializeBase(this, [firstName, lastName]);                this._title = title;            }            //修改Employee的prototype            AspNetAjaxOverView.Employee.prototype = {                get_title: function () {                    return this._title;                },                toString: function () {                    return AspNetAjaxOverView.Employee.callBaseMethod(this, "toString") +". "+ "My position is" + "  "+this.get_title() + ".";                }            }            //让employee继承person            AspNetAjaxOverView.Employee.registerClass("AspNetAjaxOverView.Employee", AspNetAjaxOverView.Person);      </script>      <!--两个按钮,alert姓名和职位-->    <input id="btnBill" type="button"  value="Bill Gates" onclick="alert(new AspNetAjaxOverView.Employee('Bill','Gates','chairman'));" />    <input  id="btnLida" type="button"  value="Li Da" onclick="alert(new AspNetAjaxOverView.Employee('Li','Da','CEO'));" />    </form></body></html>
        运行结果:

        
        在此DEMO中,使用客户端的面向对象系统编程,可以看到在ASP.NET中,更方便直观的定义类、继承等信息,这里常用的主要是注册命名空间、注册类及继承的使用方法。