How to handle lack of JavaScript Object.bind() method in IE 8

99封情书 提交于 2019-11-26 19:01:03
alexwells

There is a good compatability script on this page: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

Just copy and paste it into your script.

EDIT: placing the script below for clarity.

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

The best solution could be to install Modernizr.

Modernizr tells you whether the current browser has this feature natively implemented or not and it provides a script loader so you can pull in polyfills to backfill functionality in old browsers.

Here is the link to generate your modernizr custom version:
http://modernizr.com/download/#-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes

Function.prototype.bind isn’t supported in Internet Explorer 8 and below. Compatibility chart here: http://kangax.github.io/es5-compat-table/

Mozilla Developer Network provide this alternative for older browsers that don't implemented .bind() natively:

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

The Function constructor is the old-fashioned way of doing this:

var foo = function(x,y,z){ return Function("x,y,z","return Math.max.call(this, x, y, z)")(x,y,z) }
 
var bar = function(x,y,z){ return Function("x,y,z","return Math.min.call(this, x, y, z)")(x,y,z) }
 
console.log(foo(1,2,3) );
 
console.log(bar(3,2,1) );

References

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!