JavaScript中的prototype.bind()方法介绍

网络编程 发布日期:2024/10/10 浏览次数:1

正在浏览:JavaScript中的prototype.bind()方法介绍

以前,你可能会直接设置self=this或者that=this等等,这样做当然也能起作用,但是使用Function.prototype.bind()会更好,看上去也更专业。
下面举个简单的例子:

复制代码 代码如下:
var myObj = {
    specialFunction: function () {
    },
    anotherSpecialFunction: function () {
    },
    getAsyncData: function (cb) {
        cb();
    },
    render: function () {
        var that = this;
        this.getAsyncData(function () {
            that.specialFunction();
            that.anotherSpecialFunction();
        });
    }
};
myObj.render();

在这个例子中,为了保持myObj上下文,设置了一个变量that=this,这样是可行的,但是没有使用Function.prototype.bind()看着更整洁:
复制代码 代码如下:
render: function () {
    this.getAsyncData(function () {
        this.specialFunction();
        this.anotherSpecialFunction();
    }.bind(this));
}

在调用.bind()时,它会简单的创建一个新的函数,然后把this传给这个函数。实现.bind()的代码大概是这样的:
复制代码 代码如下:Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}
 

下面在看一个简单的使用Function.prototype.bind()的例子:

复制代码 代码如下:
var foo = {
    x: 3
};

var bar = function(){
    console.log(this.x);
};

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3
 

是不是很好用呢!不过遗憾的是IE8及以下的IE浏览器并不支持Function.prototype.bind()。支持的浏览器有Chrome 7+,Firefox 4.0+,IE 9+,Opera 11.60+,Safari 5.1.4+。虽然IE 8/7/6等浏览器不支持,但是Mozilla开发组为老版本的IE浏览器写了一个功能类似的函数,代码如下:
复制代码 代码如下:
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;
  };
}

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。