Created
August 5, 2014 18:51
-
-
Save derek/3599f91c5ea96a3f3045 to your computer and use it in GitHub Desktop.
Function.prototype.bind CoffeeScript polyfill
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
| # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility | |
| Function::bind ?= (oThis, args...) -> | |
| fNOP = -> | |
| fNOP:: ?= @:: | |
| fBound = => | |
| context = if this instanceof fNOP and oThis then this else oThis | |
| @apply context, args.concat arguments | |
| fBound:: = new fNOP() | |
| fBound |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worth noting that the original polyfill assigns
fNOP.prototypetothis.prototypeunconditionally, but whenthis.prototypeis actuallyundefined, then you breakinstanceof. This is an edge-case that you can run into when you are runningbindon a native method, such asFunction.prototype.apply.bind.So, a simple
?=fixes that issue. Shouldn't assign it a prototype that doesn't exist.Whipped this up to better understand the issue. Here's a comparison of using the faulty MDN polyfill compared to native
bindto show that the two are not equivalent.Output