Constructorification
... he he, I know the title could not be worst, but after my last post about Arrayfication I have thought: "... hey, the Thing.ify(object) could be more than handy in many occasions such mixins and duck typing ...".
So, let me introduce the Function.prototype method that nobody will ever use:
Since the function requires a Object.getOwnPropertyNames call for its prototype in order to be able to inject it's properties and methods in whatever object, the ify method is lazily assigned.
This code makes "Function.ification" easy so that precedent post could be summarized via:
and be performed at light speed every other time while it won't cost at all until it's performed on whatever constructor the first time only.
Well, at least the technique may result interesting, unfortunately without ES5 it's not possible to reproduce the same behavior without knowing in advance all possible keys part of the native prototype (it's possible for user defined ones tho)
So, let me introduce the Function.prototype method that nobody will ever use:
Function.prototype.ify = function (o) {
for (var
self = this,
p = self.prototype,
// find a fucking way to implement this in ES3
// ... uh wait, there's no way to implement
// this in ES3 ...
// https://bugzilla.mozilla.org/show_bug.cgi?id=518663
m = Object.getOwnPropertyNames(p),
i = m.length, n; i--;
) {
// methods only
m[i] = typeof p[n = m[i]] == "function" ?
"o." + n + "=p." + n + ";" : ""
;
}
m.push("return o");
return (self.ify = Function("p",
"return function " +
(self.name || "anonymous") + "fy(o){" +
m.join("") +
"}"
)(p))(o);
};
Since the function requires a Object.getOwnPropertyNames call for its prototype in order to be able to inject it's properties and methods in whatever object, the ify method is lazily assigned.
This code makes "Function.ification" easy so that precedent post could be summarized via:
Array.ify(
document.getElementsByTagName("*")
).forEach(function (node) {
// do stuff with node
});
and be performed at light speed every other time while it won't cost at all until it's performed on whatever constructor the first time only.
Well, at least the technique may result interesting, unfortunately without ES5 it's not possible to reproduce the same behavior without knowing in advance all possible keys part of the native prototype (it's possible for user defined ones tho)
Comments
Post a Comment