ObjectBoilerPlateModule - some methods to assist creating objects


/ Published in: JavaScript
Save to your folder(s)

# addMethod - By John Resig (MIT Licensed)
Add a method to an object. Creates function overloading scenario based entirely on length of argument list. Won't work to overload functions according to argument "type".

# inherit
Create parameter-less inheritance chain for situations in which the parent object takes arguments in its "constructor".

Usage:

function A(a, b) { }
function B() { A.call(this, 1, 2); }
B.prototype = inherit(A.prototype);


Copy this code and paste it in your HTML
  1. /*jslint plusplus: true, vars: true, browser: true, devel: false, maxerr: 5, maxlen: 140 */
  2. function ObjectBoilerPlateModule() {
  3. "use strict";
  4.  
  5. // addMethod - By John Resig (MIT Licensed)
  6. // add a method to an object.
  7. // creates function overloading scenario based entirely on length of argument list.
  8. // won't work to overload functions according to argument "type".
  9. function addMethod(object, name, fn) {
  10. var old = object[name];
  11. object[name] = function () {
  12. if (fn.length === arguments.length) {
  13. return fn.apply(this, arguments);
  14. }
  15.  
  16. if (typeof old === 'function') {
  17. return old.apply(this, arguments);
  18. }
  19.  
  20. throw "Invalid";
  21. };
  22. }
  23.  
  24. function inherit(parentPrototype) {
  25. function F() {}
  26. F.prototype = parentPrototype;
  27. return new F();
  28. }
  29.  
  30.  
  31. this.addMethod = addMethod;
  32. this.inherit = inherit;
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.