Class.js 1.9 KB

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