用JAVASCRIPT實現靜態對象、靜態方法和靜態屬性

來源:互聯網
上載者:User
  1. /****************************************
  2. * 方法一
  3. * 類、方法、屬性都為靜態類型
  4. * 不能建立執行個體
  5. *****************************************/
  6. var Time = {
  7.     today: ‘2009-3-8′,
  8.     weather: ‘rain’,
  9.     show: function() {
  10.         alert(‘Today is ‘ + this.today);
  11.     }
  12. };
  13.  
  14. //靜態對象可直接使用,無需建立執行個體
  15. alert(‘It is ‘ + Time.weather + ‘ today.’);
  16. Time.show();
  17.  
  18. //下面的代碼會出錯,因為靜態類不能建立執行個體
  19. //var t = new Time();
  20. //t.show();
  21.  
  22. /****************************************
  23. * 方法二
  24. * 普通對象,同時擁有靜態和非靜態屬性、方法
  25. * 可以用執行個體化
  26. * 注意:
  27. *   1.靜態方法/屬性使用類名訪問
  28. *   2.非靜態方法/屬性使用執行個體名訪問
  29. *****************************************/
  30. function Person(name) {
  31.     //非靜態屬性
  32.     this.name = name;
  33.     //非靜態方法
  34.     this.show = function() {
  35.         alert(‘My name is ‘ + this.name + ‘.’);
  36.     }
  37. }
  38. //添加靜態屬性,人都是一張嘴
  39. Person.mouth = 1;
  40. //添加靜態方法,哇哇大哭
  41. Person.cry = function() {
  42.     alert(‘Wa wa wa …’);
  43. };
  44. //使用prototype關鍵字添加非靜態屬性,每個人的牙可能不一樣多
  45. Person.prototype.teeth = 32;
  46.  
  47. //非靜態方法必須通過類的執行個體來訪問
  48. var me = new Person(‘Zhangsan’);
  49. //使用非靜態方法、屬性
  50. me.show();
  51. alert(‘I have ‘ + me.teeth + ‘ teeth.’);
  52. //使用靜態方法、屬性
  53. Person.cry();
  54. alert(‘I have ‘ + Person.mouth + ‘ mouth.’);

相關文章

聯繫我們

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