Skip to content

Instantly share code, notes, and snippets.

@chiral
Last active December 27, 2015 21:49
Show Gist options
  • Select an option

  • Save chiral/7395076 to your computer and use it in GitHub Desktop.

Select an option

Save chiral/7395076 to your computer and use it in GitHub Desktop.
attach additional methods to an obj in Javascript.
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