function.bind() not supported in IE8. make it available specifically for IE8 browsers? or keep it generic

955 Views Asked by At

I am using function.bind() in JS which is not supported in IE8 so I included below code to make it work. (referred from StackOverflow answer)

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;
      };
}

Keeping this script code for all browser will it make other browser such as IE11 slower? (which supports bind)

1

There are 1 best solutions below

2
On BEST ANSWER

The only drawback when running this code in a browser that already has .bind() is the little bit of extra code to download. When this code runs in a modern browser, it hits the first if statement and skips everything else. If .bind() is already supported, then this polyfill does not replace the existing functionality. It sees that the existing functionality is already present so it does nothing.

Polyfills like this are great to use. They let you code for modern browsers (rather than least common denominator) while still supporting older browsers. Good polyfills like this are highly recommended.


It sounds like you're unclear how this script works. What it does is the following:

  1. It checks to see if .bind() is already available on functions. If it is, then the script does nothing as it skips all the rest of its code. This is what happens in modern browsers. So, only the first if statement executes in a modern browser.
  2. If .bind() is not present, then it adds a property named bind to the Function prototype so it will be available on all function objects and assigns a function to that property. And, that function implements the standard .bind() behavior. Now, all function objects in your code will have a .bind() property no matter which browser they are running in.