Last active
December 19, 2015 05:49
-
-
Save thebyrd/5907119 to your computer and use it in GitHub Desktop.
Adds jQuery style getters and setters to a given constructor function.
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
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems like you have a couple typos there.
Function Foo
should befunction Foo
(lowercasefunction
), also missing 2 line ending escapes in the eval string.Interesting code nonetheless.