兼容IE8,Function.prototype.bind()重写

 

IE8环境下面可正常执行

    if (!Function.bind) { // ie8下可正常执行
      Function.prototype.bind = function (context) {
        if (typeof this !== 'function') {
          throw new Error('调用的对象不是方法');
        }
        var _this = this;
        var result = function () {
          return _this.apply(this instanceof result ? this : context);
        }
        var FN = function () { };
        FN.prototype = this.prototype;
        result.prototype = new FN();
        return result;
      }
    }

//demo
    var moduleTest = {
      x: 81,
      fn: function () {
        return this.x;
      }
    };

    var a = moduleTest.fn;
    console.log(a());//指向window,undefined

    var b = a.bind(moduleTest);//ie8下可正常执行
    console.log(b());//改变指向,输出 81 

 


版权声明:本文为month_ss_815原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。