5

I have a client with an original iPad and what I noticed is that it doesn't support the .bind method.

Q: If my boss insists on supporting IOS 5.1.1, is there an alternative to passing variables to a callback? I don't think I can simply put the variable into the global scope because, if I'm in a loop, the variable that I set might overwrite the same variable that the callback is looking for.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • why don't you just use underscore.js? – Daniel A. White Dec 02 '13 at 17:43
  • underscore.js? Hmmm.. I'll have to look into that! Thanks! – Phillip Senn Dec 02 '13 at 17:44
  • Google 'javascript bind shim'. – Andy Dec 02 '13 at 17:44
  • 5
    [Did you check out the Polyfill code of the MDN `.bind` page?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility) – h2ooooooo Dec 02 '13 at 17:44
  • 1
    This issue can usually be solved with a closure, but we'd have to see your actual code to show you how to do that. – jfriend00 Dec 02 '13 at 17:46
  • 2
    If you have `foo.onsomething = callback.bind(null, arg1, arg2);`, you can do `foo.onsomething = function() { callback(arg1, arg2); };` instead. Keep in mind: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example. – Felix Kling Dec 02 '13 at 17:49

2 Answers2

9

You can use the implementation provided at MDN, or even your own.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}
Tibos
  • 27,507
  • 4
  • 50
  • 64
0

In case you are using npm modules, there is even an easier solution by just doing

npm install --save polyfill-function-prototype-bind

and

require('polyfill-function-prototype-bind');

This module contains the same polyfill code as the accepted answer.

https://www.npmjs.com/package/polyfill-function-prototype-bind

danez
  • 1,659
  • 1
  • 12
  • 15