Gary Sieling

Fixing the error “TypeError: ‘undefined’ is not a function (evaluating ‘globalScope[‘console’][‘log’].bind(globalScope[‘console’])’)”

Some libraries, like PDF.js, initialize their own logging function, which wraps console.log1. If this runs in a context where function.bind does not exist, you’ll get the following error:

TypeError: 'undefined' is not a function 
(evaluating 'globalScope['console']['log'].
bind(globalScope['console'])')

Fixing this is actually quite simple- Mozilla provides a replacement function2 you can drop-in (not surprising, considering how close the behavior of bind is to call and apply).

Simply drop this code in, and you should be good to go for any environment.

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;
  };
}
  1. https://github.com/thoughtbot/capybara-webkit/issues/459 []
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind []
Exit mobile version