Last active
December 27, 2015 21:49
-
-
Save chiral/7395076 to your computer and use it in GitHub Desktop.
attach additional methods to an obj in Javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var attachMethods = function(obj,methods) { | |
| var wrap = function(a,f) { | |
| return function() { return f.apply(a,arguments); } | |
| }; | |
| for (var name in methods) { | |
| if (obj[name]) throw "conflict:"+name; | |
| obj[name] = wrap(obj,methods[name]); | |
| } | |
| return obj; | |
| } | |
| var singleton = function(methods) { | |
| return attachMethods({],methods); | |
| } | |
| /* Usage: | |
| var sysObj = some.system.getObj(); | |
| attachMethods(sysObj, { | |
| myMethod1: function(a,b,c) { | |
| this.apiFunc(a,b); // this --> sysObj | |
| }, | |
| myMethod2: function(x,y) { | |
| ... | |
| }, | |
| ... | |
| }); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment