Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Add annotated javascript of Polyfill pattern rewrite

  • Loading branch information...
1 parent d082571 commit e9076fec3027a267eb585c6ff94e414d445ff29e @d8uv d8uv committed
Showing with 30 additions and 0 deletions.
  1. +30 −0 chapters/metaprogramming/
30 chapters/metaprogramming/
@@ -30,3 +30,33 @@ However, we don't ever want to overwrite a prototype that we haven't created in
What you need to do is only add the function if it doesn't already exist. That's where the existential assignment operator (`?=`) comes in. If we do `Array::filter ?= ...` instead, it will see if `Array::filter` already exists. If it does, then it will use the current version. If it doesn't, it will add yours.
Finally, because the existential assignment operator--when compiled--creates a few variables, we clean up the code by wrapping it in an [Immediately-Invoked Function Expression (IIFE)]( This hides those internal-use-only variables from leaking outside. So, if the function we're writing already exists, it runs, does basically nothing, and exits, affecting absolutely none of your code. But, if the function we're writing *doesn't* exist, we send out only the function we're writing as a closure, so only the function you've made affects the code. The internal workings of `?=` are hidden either way.
+### Example
+Below, we've compiled and annotated the coffeescript written in the solution above
+{% highlight javascript %}
+// (function(){ ... })() is an IIFE, compiled in thanks to `do ->`
+(function() {
+ // This is from the `?=` operator, used to check if Array.prototype.filter (`Array::filter`) exists.
+ // If it does, we set it to itself, and return. If it doesn't, then we set it to the function, and return the function.
+ // The IIFE is only used to hide _base and _ref from the outside world.
+ var _base, _ref;
+ return (_ref = (_base = Array.prototype).filter) != null ? _ref : _base.filter = function(callback) {
+ // `element for element in this when callback element`
+ var element, _i, _len, _results;
+ _results = [];
+ for (_i = 0, _len = this.length; _i < _len; _i++) {
+ element = this[_i];
+ if (callback(element)) {
+ _results.push(element);
+ }
+ }
+ return _results;
+ };
+// The end of the IIFE from `do ->`
+{% endhighlight %}

0 comments on commit e9076fe

Please sign in to comment.
Something went wrong with that request. Please try again.