JavaScript中的prototype.bind()方法介紹
以前,你可能會直接設(shè)置self=this或者that=this等等,這樣做當然也能起作用,但是使用Function.prototype.bind()會更好,看上去也更專業(yè)。
下面舉個簡單的例子:
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上下文,設(shè)置了一個變量that=this,這樣是可行的,但是沒有使用Function.prototype.bind()看著更整潔:
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
在調(diào)用.bind()時,它會簡單的創(chuàng)建一個新的函數(shù),然后把this傳給這個函數(shù)。實現(xiàn).bind()的代碼大概是這樣的:
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+,F(xiàn)irefox 4.0+,IE 9+,Opera 11.60+,Safari 5.1.4+。雖然IE 8/7/6等瀏覽器不支持,但是Mozilla開發(fā)組為老版本的IE瀏覽器寫了一個功能類似的函數(shù),代碼如下:
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;
};
}
- javascript中的Function.prototye.bind
- javascript之bind使用介紹
- js apply/call/caller/callee/bind使用方法與區(qū)別分析
- js bind 函數(shù) 使用閉包保存執(zhí)行上下文
- js設(shè)置組合快捷鍵/tabindex功能的方法
- javascript bind綁定函數(shù)代碼
- javascript中bind函數(shù)的作用實例介紹
- 淺談javascript中call()、apply()、bind()的用法
- JS中改變this指向的方法(call和apply、bind)
- 深入理解JS中的Function.prototype.bind()方法
相關(guān)文章
Javascript學(xué)習(xí)筆記9 prototype封裝繼承
在上文中,我利用prototype的原理做了一個封裝的New,然后我就想到,我是否可以用prototype的原理進一步封裝面向?qū)ο蟮囊恍┗咎卣髂??比如繼承。2010-01-01
JavaScript高級程序設(shè)計(第3版)學(xué)習(xí)筆記11 內(nèi)建js對象
內(nèi)建對象是指由ECMAScript實現(xiàn)提供的、不依賴于宿主環(huán)境的對象,這些對象在程序運行之前就已經(jīng)存在了2012-10-10
Javascript基礎(chǔ)教程之定義和調(diào)用函數(shù)
這篇文章主要介紹了Javascript基礎(chǔ)教程之定義和調(diào)用函數(shù)的相關(guān)資料,需要的朋友可以參考下2015-01-01
ASP.NET實現(xiàn)Repeater控件的數(shù)據(jù)綁定
這篇文章介紹了ASP.NET實現(xiàn)Repeater控件數(shù)據(jù)綁定的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
Javascript基礎(chǔ) 函數(shù)“重載” 詳細介紹
這篇文章介紹了Javascript基礎(chǔ) 函數(shù)“重載” ,有需要的朋友可以參考一下2013-10-10
Javascript基礎(chǔ)_簡單比較undefined和null 值
下面小編就為大家?guī)硪黄狫avascript基礎(chǔ)_簡單比較undefined和null 值。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06

