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.’);

 posted on 2011-06-16 11:38  H&M  阅读(238)  评论(0编辑  收藏  举报