Facebook’s JS SDK has recently started using newer ES5 Javascript methods such as Object.keys() and [].map(). They still support older browsers by having an ES5() function that accepts the original object, the name of the desired method, and any parameters. It then runs either the native method or an equivalent JS method if the native one isn’t available. For example:
ES5(g.api.whitelist, 'forEach', true, function(ca) {
s[ca] = 1;
});
or for top-level objects,
ES5('JSON', 'parse', false, r.responseText);
I suspect that this is the result of a preprocessor, and FB’s devs are actually writing something more along the lines of
g.api.whitelist.forEach(function(ca) {
s[ca] = 1;
});
and
JSON.parse(r.responseText);
(presumably with longer variable names too)
Now, assuming I’m right that there is a preprocessor, is the ES5() function and associated preprocessed are an open-source project or something in-house? If it’s in-house, can anyone from FB comment on the possibility of open-sourcing it? It’s something that I could find tremendously useful.
We are indeed using a preprocessor (based on jspatch) which lets us write regular ES5 code. The
ES5function itself is basically a wrapper around polyfills from MDN and JSON3.Not only does this let us write ES5, but it avoids us using faulty implementations of things like Function#bind and
JSON.stringify.The blog post is now out.