iOS5不支持bind()!

Phi*_*enn 5 javascript bind

我有一个原始iPad的客户端,我注意到它不支持.bind方法.

问:如果我的老板坚持支持IOS 5.1.1,是否可以选择将变量传递给回调?我不认为我可以简单地将变量放入全局范围,因为如果我处于循环中,我设置的变量可能会覆盖回调所需的同一变量.

Tib*_*bos 9

您可以使用MDN提供的实现,甚至是您自己的实现.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility

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;
  };
}
Run Code Online (Sandbox Code Playgroud)