Function.bind () is not supported in IE8. to make it available specifically for IE8 browsers? or keep it shared

I am using function.bind () in JS which is not supported in IE8 so I have included below code to make it work. (links to 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 browsers will cause another browser like IE11 to be slower? (which bind supports)

+3


source to share


1 answer


The only drawback when running this code in a browser that it already has .bind()

is a little extra code to download. When this code runs in a modern browser, it hits the first statement if

and skips over everything else. If .bind()

already supported, then this polyfill does not replace existing functionality. He sees that the existing functionality is already there, so he does nothing.

Poly-shelves like this are easy to use. They allow you to code for modern browsers (rather than the lowest common denominator) while still supporting older browsers. Good policies like this are highly recommended.




It looks like you misunderstood how this script works. It does the following:

  • It checks if it is available .bind()

    for functions. If so, then the script does nothing, as it skips all the rest of the code. This is what happens in modern browsers. Thus, only the first statement if

    is executed in a modern browser.
  • If .bind()

    not, then it adds a named property bind

    to the prototype Function

    , so it will be available to all function objects and assigns a function to that property. And this function implements the standard behavior .bind()

    . Now, all function objects in your code will have a property .bind()

    no matter what browser they are running in.
+3


source







All Articles