兼容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 
ss-
发布了20 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/month_ss_815/article/details/87372157
今日推荐