萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JavaScript中的prototype.bind()方法介紹

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

 在JavaScript中,我們經常用到函數綁定,而當你需要在另一個函數中保持this上下文時,使用Function.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;   }; }
copyright © 萬盛學電腦網 all rights reserved