javascript 類和命名空間的類比

來源:互聯網
上載者:User
文章目錄
  • 1.類的類比
  • 2.命名空間的類比
  • 4.目標:調用類的靜態函數

就當我是重複造輪子吧,整理該文檔給有需要的人用,包括我:)

先上一段最簡單的:

// 以下幾行代碼展示了命名空間、類、以及函數的類比定義和使用:
NameSpace = {};
NameSpace.Class = function(){
  this.Method = function(info){alert(info);}
};
new NameSpace.Class().Method("Hello world");

 

 

再來一些可見到的,各種情況的代碼

1.類的類比  // 類定義
  function Class(info){
    // 私人成員
    var privateData = "private data";
    var privateMethod = function(){writeline("private");};
    function privateMethod2(info){writeline("private");}

    // 公有成員(使用this)
    this.Data = "public data";
    this.Method = function(){writeline(info);};
  };
  
  // 類的靜態成員
  Class.StaticData = "static data";
  Class.StaticMethod = function(info){writeline(info);};

 

 

2.命名空間的類比

function NameSpace(){}
或者
NameSpace = {};
或者
NameSpace = new Object();

 


3.目標:建立類執行個體,並調用執行個體方法

var o = new NameSpace.Class("hello world");

o.Method();

  // 使用已有的類定義,並用靜態方法掛到NameSpace下
  NameSpace.Class1 = Class;
  new NameSpace.Class1("new NameSpace.Class1().Method()").Method();

  // 或者:建立類定義
  NameSpace.Class2 = function(info){
    this.Method = function(){writeline(info);};
  };
  new NameSpace.Class2("new NameSpace.Class2().Method()").Method();

 

 

4.目標:調用類的靜態函數

NameSpace.Class.StaticMethod();

  // 靜態對象+靜態方法
  NameSpace.Class3 = {};  // {}表示這是一個對象,或者用new object();
  NameSpace.Class3.Method = function(info) {writeline(info);};
  NameSpace.Class3.Method("NameSpace.Class3.Method()");

  // 或者:new一個對象賦予靜態成員
  NameSpace.Class4 = new Class("NameSpace.Class4.Method()");
  NameSpace.Class4.Method();
  
  // 或者:匿名函數用於定義類,再用new建立對象
  NameSpace.Class5 = new (function(info){
    this.Method = function(){writeline(info);};
  })("NameSpace.Class5.Method()");
  NameSpace.Class5.Method();
  
  // 或者:JSON方式(類定義+建立同時完成)
  // 優點是簡單,缺點是不能傳遞參數進去
  NameSpace.Class6 = {
    Method : function(info){writeline(info);}
  };
  NameSpace.Class6.Method("NameSpace.Class6.Method()");

 

代碼下載:/Files/surfsky/oo.htm

ps.很開心,vs2010對js的智能感知越來越好用了:p

 

相關文章

聯繫我們

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