diff options
author | matthewsotoudeh <matthewsot@outlook.com> | 2015-05-10 17:40:27 -0700 |
---|---|---|
committer | matthewsotoudeh <matthewsot@outlook.com> | 2015-05-10 17:40:27 -0700 |
commit | 393e4f220fafcaade28d31f49d16381099d6591a (patch) | |
tree | e22b005e411bf2febc626c7fe43121a2d269098d | |
parent | 53fbda210ef4404d3049d0fcd2b8261d1a61f585 (diff) |
basic overloadable functions
-rw-r--r-- | README.md | 15 | ||||
-rw-r--r-- | jfn.js | 54 |
2 files changed, 69 insertions, 0 deletions
@@ -1,2 +1,17 @@ # jfn Playing around with Javascript functions + +A global overloadable function: + +``` +jfn.defineFunction("testFunction", ["string"], function (str) { + alert("String: " + str); +}); + +jfn.defineFunction("testFunction", ["number"], function (num) { + alert("Num: " + num); +}); + +testFunction("Hello!"); //String: Hello! +testFunction(1); //Num: 1 +```
\ No newline at end of file @@ -0,0 +1,54 @@ +var jfn = {}; + +jfn.getProxyFunction = function (name) { + return function () { + var jfns = this[name]["__jfns"]; + + for (var i = 0; i < jfns.length; i++) { + var jfn = jfns[i]; + + var matches = arguments.length === jfn.args.length; + for (var a = 0; a < jfn.args.length; a++) { + matches = jfn.args[a] === (typeof arguments[a]); + if (!matches) { + break; + } + } + + if (matches) { + jfn.fn.apply(this, arguments); + return; + } + } + }; +}; + +jfn.defineFunction = function (object, name, args, fn) { + if (typeof object === "string") { + fn = args; + args = name; + name = object; + object = window; + } + + if (!object.hasOwnProperty(name)) { + object[name] = jfn.getProxyFunction(name); + } + + if (!object[name].hasOwnProperty("__jfns")) { + object[name]["__jfns"] = []; + } else { + for (var i = 0; i < object[name]["__jfns"].length; i++) { + var f = object[name]["__jfns"][i]; + if (JSON.stringify(f.args) === JSON.stringify(args)) { + object[name]["__jfns"].splice(i, 1); + return; + } + } + } + + object[name]["__jfns"].push({ + args: args, + fn: fn + }); +};
\ No newline at end of file |