如何处理IE 8中JavaScript Object.bind()方法的缺失

我正在写一些使用Object.bind方法的JavaScript。

 funcabc = function(x, y, z){ this.myx = x; this.playUB = function(w) { if ( this.myx === null ) { // do blah blah return; } // do other stuff }; this.play = this.playUB.bind(this); }; 

由于我在WinXP中用Firefox开发,有时候用IE9或者10testingWin7,所以我没有注意到或者注意到IE8和下面不支持bind的事实。

这个特定的脚本不使用canvas,所以我有点犹豫是否注销所有的IE 8用户。

有标准的解决方法吗?

我在JavaScript中得到了一些好处,但我仍然是一个小白菜。 所以请原谅我,如果解决scheme是完全明显的。

这个页面上有一个很好的兼容性脚本: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

只需复制并粘贴到您的脚本。

编辑:放置下面的脚本清晰。

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

最好的解决办法是安装Modernizr 。

Modernizr告诉你当前的浏览器是否具有本地实现的这个function,它提供了一个脚本加载器,这样你就可以在旧的浏览器中使用polyfill来回填function。

这里是生成你的modernizr定制版本的链接:
http://modernizr.com/download/#-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes

Internet Explorer 8及以下版本不支持Function.prototype.bind。 兼容性图表在这里: http : //kangax.github.io/es5-compat-table/

Mozilla开发者networking为旧版本的浏览器提供了这个替代方法,它本身并没有实现.bind()

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

Function构造函数是这样做的老式方法:

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