Class.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var extend = require('./extend');
  2. var toArr = require('./toArr');
  3. var inherits = require('./inherits');
  4. var safeGet = require('./safeGet');
  5. var isMiniProgram = require('./isMiniProgram');
  6. exports = function(methods, statics) {
  7. return Base.extend(methods, statics);
  8. };
  9. function makeClass(parent, methods, statics) {
  10. statics = statics || {};
  11. var className =
  12. methods.className || safeGet(methods, 'initialize.name') || '';
  13. delete methods.className;
  14. var ctor = function() {
  15. var args = toArr(arguments);
  16. return this.initialize
  17. ? this.initialize.apply(this, args) || this
  18. : this;
  19. };
  20. if (!isMiniProgram) {
  21. try {
  22. ctor = new Function(
  23. 'toArr',
  24. 'return function ' +
  25. className +
  26. '()' +
  27. '{' +
  28. 'var args = toArr(arguments);' +
  29. 'return this.initialize ? this.initialize.apply(this, args) || this : this;' +
  30. '};'
  31. )(toArr);
  32. } catch (e) {}
  33. }
  34. inherits(ctor, parent);
  35. ctor.prototype.constructor = ctor;
  36. ctor.extend = function(methods, statics) {
  37. return makeClass(ctor, methods, statics);
  38. };
  39. ctor.inherits = function(Class) {
  40. inherits(ctor, Class);
  41. };
  42. ctor.methods = function(methods) {
  43. extend(ctor.prototype, methods);
  44. return ctor;
  45. };
  46. ctor.statics = function(statics) {
  47. extend(ctor, statics);
  48. return ctor;
  49. };
  50. ctor.methods(methods).statics(statics);
  51. return ctor;
  52. }
  53. var Base = (exports.Base = makeClass(Object, {
  54. className: 'Base',
  55. callSuper: function(parent, name, args) {
  56. var superMethod = parent.prototype[name];
  57. return superMethod.apply(this, args);
  58. },
  59. toString: function() {
  60. return this.constructor.name;
  61. }
  62. }));
  63. module.exports = exports;