Class.create.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Simple JavaScript Inheritance
  2. * By John Resig http://ejohn.org/
  3. * MIT Licensed.
  4. */
  5. // Inspired by base2 and Prototype
  6. (function(){
  7. var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  8. // The base Class implementation (does nothing)
  9. this.Class = function(){};
  10. // Create a new Class that inherits from this class
  11. Class.extend = function(prop) {
  12. var _super = this.prototype;
  13. // Instantiate a base class (but only create the instance,
  14. // don't run the init constructor)
  15. initializing = true;
  16. var prototype = new this();
  17. initializing = false;
  18. // Copy the properties over onto the new prototype
  19. for (var name in prop) {
  20. // Check if we're overwriting an existing function
  21. prototype[name] = typeof prop[name] == "function" &&
  22. typeof _super[name] == "function" && fnTest.test(prop[name]) ?
  23. (function(name, fn){
  24. return function() {
  25. var tmp = this._super;
  26. // Add a new ._super() method that is the same method
  27. // but on the super-class
  28. this._super = _super[name];
  29. // The method only need to be bound temporarily, so we
  30. // remove it when we're done executing
  31. var ret = fn.apply(this, arguments);
  32. this._super = tmp;
  33. return ret;
  34. };
  35. })(name, prop[name]) :
  36. prop[name];
  37. }
  38. // The dummy class constructor
  39. function Class() {
  40. // All construction is actually done in the init method
  41. if ( !initializing && this.init )
  42. this.init.apply(this, arguments);
  43. }
  44. // Populate our constructed prototype object
  45. Class.prototype = prototype;
  46. // Enforce the constructor to be what we expect
  47. Class.constructor = Class;
  48. // And make this class extendable
  49. Class.extend = arguments.callee;
  50. return Class;
  51. };
  52. })();