JavaScript中的prototype.bind()方法介紹
以前,你可能會(huì)直接設(shè)置self=this或者that=this等等,這樣做當(dāng)然也能起作用,但是使用Function.prototype.bind()會(huì)更好,看上去也更專業(yè)。
下面舉個(gè)簡(jiǎn)單的例子:
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
this.getAsyncData(function () {
that.specialFunction();
that.anotherSpecialFunction();
});
}
};
myObj.render();
在這個(gè)例子中,為了保持myObj上下文,設(shè)置了一個(gè)變量that=this,這樣是可行的,但是沒有使用Function.prototype.bind()看著更整潔:
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
在調(diào)用.bind()時(shí),它會(huì)簡(jiǎn)單的創(chuàng)建一個(gè)新的函數(shù),然后把this傳給這個(gè)函數(shù)。實(shí)現(xiàn).bind()的代碼大概是這樣的:
var fn = this;
return function () {
return fn.apply(scope);
};
}
下面在看一個(gè)簡(jiǎn)單的使用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瀏覽器寫了一個(gè)功能類似的函數(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ù)的作用實(shí)例介紹
- 淺談javascript中call()、apply()、bind()的用法
- JS中改變this指向的方法(call和apply、bind)
- 深入理解JS中的Function.prototype.bind()方法
相關(guān)文章
JavaScript 瀏覽器驗(yàn)證代碼(來自discuz)
很多時(shí)候需要用js判定瀏覽器的版本等信息,這里的代碼是從discuz看到的,其實(shí)大家學(xué)習(xí)的時(shí)候也可以這樣。2010-07-07簡(jiǎn)介JavaScript中fixed()方法的使用
這篇文章主要介紹了JavaScript中fixed()方法的使用,是JS入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-06-06JavaScript數(shù)組的快速克隆(slice()函數(shù))和數(shù)組的排序、亂序和搜索(sort()函數(shù))
JavaScript數(shù)組的快速克隆(slice()函數(shù))和數(shù)組的排序、亂序和搜索(sort()函數(shù))...2006-12-12JavaScript Try...Catch 聲明的 使用方法
JavaScript Try...Catch 聲明的 使用方法...2007-04-04