Skip to content

Instantly share code, notes, and snippets.

@thebyrd
Last active December 19, 2015 05:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebyrd/5907119 to your computer and use it in GitHub Desktop.
Save thebyrd/5907119 to your computer and use it in GitHub Desktop.
Adds jQuery style getters and setters to a given constructor function.
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
var getParamNames = function (func) {
var funStr = func.toString()
return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g)
}
function addMagicMethod (Constructor) {
var params = getParamNames(Constructor)
for (var j = 0; j < params.length; j++) {
eval('\
var magicMethod = function (v) {\
if (v) {\
this._' + params[j] + ' = v;\
return this;\
} else {\
return this._' + params[j] + ';
}
}')
Constructor.method(params[j], magicMethod)
}
}
// example
Function Foo (a, b, c) {}
addMagicMethod(Foo)
var f = new Foo()
f.a("Magic")
f.a() // returns "Magic"
f.b("Something Else")
f.b() // returns "Something Else"
f.c("More")
f.c() // returns "More"
@UltCombo
Copy link

UltCombo commented Feb 5, 2014

Seems like you have a couple typos there. Function Foo should be function Foo (lowercase function), also missing 2 line ending escapes in the eval string.

Interesting code nonetheless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment