function.bind() 在 IE8 中不受支持。使其专门用于 IE8 浏览器?或者保持通用

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

我在 IE8 不支持的 JS 中使用 function.bind(),所以我包含了下面的代码以使其工作。 (引用自 Whosebug 答案)

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

为所有浏览器保留此脚本代码是否会使其他浏览器(例如IE11)变慢? (支持绑定)

当 运行 在已有 .bind() 的浏览器中使用此代码时,唯一的缺点是要下载一点额外的代码。当此代码在现代浏览器中运行时,它会命中第一个 if 语句并跳过其他所有内容。如果 .bind() 已经被支持,那么这个 polyfill 不会替换现有的功能。它发现现有功能已经存在,因此它什么都不做。

像这样的 Polyfills 很好用。它们允许您为现代浏览器(而不是最小公分母)编写代码,同时仍然支持旧浏览器。强烈推荐像这样好的 polyfill。


听起来你不清楚这个脚本是如何工作的。它的作用如下:

  1. 它会检查 .bind() 是否已在函数上可用。如果是,那么脚本将不执行任何操作,因为它会跳过所有其余代码。这就是现代浏览器中发生的事情。因此,只有第一个 if 语句在现代浏览器中执行。
  2. 如果 .bind() 不存在,那么它会添加一个名为 bind 的 属性 到 Function 原型,这样它就可以在所有函数对象上使用并分配一个属性 的功能。而且,该函数实现了标准的 .bind() 行为。现在,代码中的所有函数对象都将具有 .bind() 属性,无论它们在哪个浏览器中 运行。