cclass.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. /**
  17. * cclass is a javascript Class inheritance implementation.
  18. * Methods and class members should be in the second argument.
  19. * This ensures that they end up in the prototype of the function
  20. * and makes them available to each new object.
  21. *
  22. * Example Usage:
  23. * var A = cclass.create(function() {
  24. * this.instance_member = 'foo';
  25. * }, {
  26. * test: function() {;
  27. * // do something!!!
  28. * }});
  29. *
  30. * var B = A.extend(function() {
  31. * this.__proto__.constructor();
  32. * }, {
  33. * static_member: 'bob',
  34. * test: function(){
  35. * this.parent.test();
  36. * }
  37. * });
  38. *
  39. * var a = new B();
  40. * a.test();
  41. *
  42. */
  43. var cclass = (function($, undefined) {
  44. function extend(ext_fn, attrs) {
  45. function parent() {};
  46. // Need a function to create an object from.
  47. // The 'fn' function will use 'ext_fn' as its initializer.
  48. // We don't use 'ext_fn' itself since we modify the function extensively.
  49. function fn() {
  50. ext_fn.apply(this, arguments);
  51. };
  52. // 'this' should be the caller.
  53. // Should be a 'cclass' object.
  54. parent.prototype = this.prototype;
  55. // Create a 'class' members region via prototype chain.
  56. // If a method is not part of the object, it will check its
  57. // prototype chain.
  58. fn.prototype = new parent();
  59. // The constructor should be the copy of 'ext_fn'.
  60. fn.prototype.constructor = fn;
  61. fn.extend = extend;
  62. $.extend(fn.prototype, attrs || {}, {
  63. parent: parent.prototype
  64. });
  65. return fn;
  66. }
  67. return {
  68. create: function(fn, attrs) {
  69. $.extend(fn.prototype, attrs || {});
  70. fn.extend = extend;
  71. fn.parent = undefined;
  72. return fn;
  73. },
  74. extend: extend
  75. };
  76. })($, undefined);