Class.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. FC.Class = Class; // export
  2. // Class that all other classes will inherit from
  3. function Class() { }
  4. // Called on a class to create a subclass.
  5. // Last argument contains instance methods. Any argument before the last are considered mixins.
  6. Class.extend = function() {
  7. var len = arguments.length;
  8. var i;
  9. var members;
  10. for (i = 0; i < len; i++) {
  11. members = arguments[i];
  12. if (i < len - 1) { // not the last argument?
  13. mixIntoClass(this, members);
  14. }
  15. }
  16. return extendClass(this, members || {}); // members will be undefined if no arguments
  17. };
  18. // Adds new member variables/methods to the class's prototype.
  19. // Can be called with another class, or a plain object hash containing new members.
  20. Class.mixin = function(members) {
  21. mixIntoClass(this, members);
  22. };
  23. function extendClass(superClass, members) {
  24. var subClass;
  25. // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
  26. if (hasOwnProp(members, 'constructor')) {
  27. subClass = members.constructor;
  28. }
  29. if (typeof subClass !== 'function') {
  30. subClass = members.constructor = function() {
  31. superClass.apply(this, arguments);
  32. };
  33. }
  34. // build the base prototype for the subclass, which is an new object chained to the superclass's prototype
  35. subClass.prototype = createObject(superClass.prototype);
  36. // copy each member variable/method onto the the subclass's prototype
  37. copyOwnProps(members, subClass.prototype);
  38. // copy over all class variables/methods to the subclass, such as `extend` and `mixin`
  39. copyOwnProps(superClass, subClass);
  40. return subClass;
  41. }
  42. function mixIntoClass(theClass, members) {
  43. copyOwnProps(members, theClass.prototype);
  44. }