學習筆記 —— Javascript的類(3)

來源:互聯網
上載者:User
//定義一個類
function TestClass(name)
{
    //初始化時總數+1
    TestClass.prototype.Count++;

    //定義一個屬性,並設定預設值
    this.Name = name || "jxh";

    //定義一個靜態類屬性
    TestClass.prototype.Current.InternalName = this.Name;

    //定義一個對象屬性
    this.internalClass = new InternalClass(this.Name);

    //定義一個方法
    this.GetFormatName = function()
    {
        var fname = this.internalClass.FormatName();
        return fname;
    }
}

//為TestClass類定義一個靜態屬性
TestClass.prototype.Count = 0;

//為TestClass類定義一個靜態類屬性
TestClass.prototype.Current = new InternalClass("沒有執行個體");

//內部類
function InternalClass(name)
{
    this.InternalName = name;
}

對於靜態屬性的訪問,除了 [類名.prototype.屬性名稱] 的訪問方式外,直接用 [對象名.屬性名稱] 也能訪問,但由於 [對象名.屬性名稱] 的訪問方式如果對屬性做了修改的話, [對象名.屬性名稱] 將不在和 [類名.prototype.屬性名稱] 的值一致,可能會引起誤會,所以建議對靜態屬性只使用[類名.prototype.屬性名稱] 一種方式去訪問。<script language = "javascript">
    function Click_Event()
    {
        alert("沒有執行個體對象");
        alert("TestClass.prototype.Count:" + TestClass.prototype.Count);
        alert("TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);

        var testClass1 = new TestClass(); 
        alert("執行個體1個對象");
        alert("TestClass.prototype.Count:" + TestClass.prototype.Count);
        alert("TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);

        var testClass2 = new TestClass("jxhwei"); 
        alert("執行個體2個對象");
        alert("TestClass.prototype.Count:" + TestClass.prototype.Count);
        alert("TestClass.prototype.Current:" + TestClass.prototype.Current.InternalName);
    }
</script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.