Use JavaScript to implement static objects, static methods, and static attributes

Source: Internet
Author: User
  1. /*************************************** *
  2. * Method 1
  3. * All classes, methods, and properties are static types.
  4. * You cannot create an instance.
  5. **************************************** */
  6. VaR time = {
  7. Today: '2017-3-8 ′,
  8. WEATHER: 'rain ',
  9. Show: function (){
  10. Alert ('Today is '+ this. Today );
  11. }
  12. };
  13.  
  14. // Static objects can be used directly without the need to create an instance
  15. Alert ('it is '+ time. Weather + 'today .');
  16. Time. Show ();
  17.  
  18. // The following code will fail because the static class cannot create an instance.
  19. // Var T = new time ();
  20. // T. Show ();
  21.  
  22. /*************************************** *
  23. * Method 2
  24. * Common objects with static and non-static attributes and Methods
  25. * Instantiation can be used.
  26. * Note:
  27. * 1. Use the class name to access static methods/Properties
  28. * 2. Use the Instance name to access non-static methods/attributes
  29. **************************************** */
  30. Function person (name ){
  31. // Non-static attributes
  32. This. Name = Name;
  33. // Non-static method
  34. This. Show = function (){
  35. Alert ('My name is '+ this. Name + '.');
  36. }
  37. }
  38. // Add static attributes. All users are talking.
  39. Person. Mouth = 1;
  40. // Add a static method.
  41. Person. Cry = function (){
  42. Alert ('wa Wa wa... ');
  43. };
  44. // Use the prototype keyword to add non-static attributes. Each user may have different teeth.
  45. Person. Prototype. Teeth = 32;
  46.  
  47. // Non-static methods must be accessed through class instances
  48. VaR me = new person ('hangsan ');
  49. // Use non-static methods and attributes
  50. Me. Show ();
  51. Alert ('I have' + me. Teeth + 'teeth .');
  52. // Use static methods and attributes
  53. Person. Cry ();
  54. Alert ('I have' + person. Mouth + 'mouth .');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.