javascript 編寫自己的架構

來源:互聯網
上載者:User

看了itcast裡面老師的講課,下面是我一些體會

Code
(function(){
          window['czf'] = {}\\ 命名空間
          
         var $$= function(){
               alert('這個是私人的方法');
          }
          window['czf']["$"] = $$;

                $11= function (){
        alert("這個是public方法"); \\直接調用
          }
                function fn(){
                     alert("這個也是私人"); \\=var a=function(){}
                }

}();

這裡可以分有2步來
var fn = function(){};
fn();

這裡$11相當與是全域變數,可以任意調用,一般是用window['czf']["$"] = $$; 可以有自己的命名空間。

html

Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script type="text/javascript" src="czf.js" ></script>
</head>

<body onload="$11();">
<input type="button" onclick = "czf.$();"/>
</body>
</html>

還有一種寫法

Code
function(){
var MSDNMagNS = {};

MSDNMagNS.Pet = function(name) { alert(name);  };
MSDNMagNS.Pet.prototype.toString = function() { 
    alert('prototype.tostring'); 
};

MSDNMagNS.Pet.toString = function() {
     alert("Pet.toString ");
};

var pet = new MSDNMagNS.Pet('Yammer');
pet.toString();\\輸出prototype.tostring

}();

之前一直對prototype不理解,通過這個例子可以知道了
在new 對象時候,添加對象的屬性或方法。

下面的例子,大家也可以測試看看

var a=function()
{
    $1=function(){
        alert("OKYZX");
    };
    //$1();

    this.$2 = function(){
        alert("OK$2");
    }
};

a.prototype.$r = function(){
    alert("a.prototype.$r,必須執行個體化");
}
a.$3 = function (){
    alert("OK,$3");
}
a();

$1();

var aa = new a();
aa.$2();//內部一個方法
aa.$r();//必須執行個體化,才可以調用

a.$3();

 

推薦大家去看看JavaScript 進階程式設計,第二書店有連載,不錯的說。

 

聯繫我們

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