Achieve static objects with JAVASCRIPT, static methods and static properties

Javascript object-oriented features of the language is weak, other object-oriented languages ​​when creating a class just use the static keyword to specify the class as a static class, Javascript does not provide a keyword such as static, Javascript also have to make a "static" characteristics only by Some "clever but useless" the.

A code implementations include two kinds of static methods / attributes of a class is a static properties and static methods, static methods and other properties, non-static class code description are written in each line in the code comments, where not repeat.

JAVASCRIPT:

 

  1. /****************************************
  2. * method one
  3. * Classes, methods, properties are static type
  4. * You can not create an instance
  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. // static object can be used directly, without having to create an instance
  15. alert ( ‘It is ‘  + Time. weather  +   ‘ today.’ );
  16. Time. show ( );
  17.  
  18. // The following code will be wrong, because the static class can not create an instance
  19. // var t = new Time ();
  20. //t.show();
  21.  
  22. /****************************************
  23. * Method Two
  24. * Ordinary objects, have both static and non-static properties, methods
  25. * Can be instantiated
  26. * Note:
  27. * 1. Static method / property using the class name to access
  28. * 2. Non-static method / property using the instance name to access
  29. *****************************************/
  30. function  Person ( name )   {
  31.       // non-static properties
  32.       this. name  =   name;
  33.       // non-static method
  34.       this. show  =   function ( )   {
  35.           alert ( ‘My name is ‘  +   this. name  +   ‘.’ );
  36.       }
  37. }
  38. // add static properties, but every man a mouth
  39. Person. mouth  =   1;
  40. // add a static method, cried
  41. Person. cry  =   function ( )   {
  42.       Alert ( 'Wa Wa Wa ...' ) ;
  43. };
  44. // add non-static properties using the prototype keyword, each person's teeth may not be as much
  45. Person. prototype. teeth  =   32;
  46.  
  47. // non-static methods must be accessed through instances of the class
  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.’ );

转载于:https://www.cnblogs.com/200831856/archive/2009/09/15/javascript_static_1.html

Guess you like

Origin blog.csdn.net/weixin_33937778/article/details/93711356