Atlas學習手記(27):JavaScript物件導向的擴充(一):命名空間Namespace

來源:互聯網
上載者:User

在Javascript中並沒有空間、類、介面這些概念,Atlas對這些東西實現封裝了,增強了JavaScript物件導向方面的能力,本文看一下如何使用命名空間。

 

主要內容

1.概述

2.完整樣本

 

一.概述

在Javascript中並沒有空間、類、介面這些概念,Atlas對這些東西進行了封裝,增強了JavaScript物件導向方面的能力,本文看一下如何使用命名空間。在使用命名空間時有兩個方法是需要我們注意的。

registerNamespace:註冊一個命名空間

registerClass:註冊一個類到某個命名空間中

二.完整樣本

1.建立一個Atlas Web Site後,添加一個Namespace.js的檔案,在這裡我們註冊一個Demo的命名空間,並建立Person類,把它註冊到Demo命名空間中,如下所示:

// JScript File

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {

    var _firstName = firstName;

    var _lastName = lastName;

    var _emailAddress = emailAddress;

    this.getFirstName = function() {

        return _firstName;

    }

    this.getLastName = function() {

        return _lastName;

    }

    this.getName = function() {

        return _firstName + ' ' + _lastName;

    }

    this.dispose = function() {

        alert('bye ' + this.getName());

    }

}

Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

2.在ASPX頁面中添加ScriptManager,這個總是不能少的:

<atlas:ScriptManager runat="server" ID="scriptManager" />

3.引入我們剛才建立的JS檔案:

<script type="text/javascript" src="Namespace.js"></script>

4.現在就可以在前端指令碼中調用了:

<script type="text/javascript" language="JavaScript">

function OnButton1Click() 

{

    var testPerson = new Demo.Person('John', 'Smith', 'john.smith@example.com');

    alert(testPerson.getFirstName() + " " + testPerson.getLastName() );

    return false;

}

</script>

5.添加一個Button,在它的單擊事件中來調用:

<div>

        This example and puts the Person class in the "Demo" namespace.

        <br />

        <br />

        <input id="Button1" value="Create Demo.Person" type="button" onclick="return OnButton1Click()" />

</div>

看看上面編寫的代碼,是不是很有物件導向的感覺呢?編譯運行:


單擊按鈕後:

完整樣本下載:http://files.cnblogs.com/Terrylee/AtlasNamespaceDemo.rar

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.