淺析Javascript中bind()方法的使用與實(shí)現(xiàn)
我們先來(lái)看一道題目
var write = document.write;
write("hello");
//1.以上代碼有什么問(wèn)題
//2.正確操作是怎樣的
不能正確執(zhí)行,因?yàn)閣rite函數(shù)丟掉了上下文,此時(shí)this的指向global或window對(duì)象,導(dǎo)致執(zhí)行時(shí)提示非法調(diào)用異常,所以我們需要改變this的指向
正確的方案就是使用 bind/call/apply來(lái)改變this指向
bind方法
var write = document.write;
write.bind(document)('hello');
call方法
var write = document.write; write.call(document,'hello');
apply方法
var write = document.write; write.apply(document,['hello']);
bind函數(shù)
bind()最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù),使這個(gè)函數(shù)不論怎么調(diào)用都有同樣的this值。常見(jiàn)的錯(cuò)誤就像上面的例子一樣,將方法從對(duì)象中拿出來(lái),然后調(diào)用,并且希望this指向原來(lái)的對(duì)象。如果不做特殊處理,一般會(huì)丟失原來(lái)的對(duì)象。使用bind()方法能夠很漂亮的解決這個(gè)問(wèn)題:
<script type="text/javascript">
this.num = 9;
var module = {
num: 81,
getNum: function(){
console.log(this.num);
}
};
module.getNum(); // 81 ,this->module
var getNum = module.getNum;
getNum(); // 9, this->window or global
var boundGetNum = getNum.bind(module);
boundGetNum(); // 81,this->module
</script>
偏函數(shù)(Partial Functions)
Partial Functions也叫Partial Applications,這里截取一段關(guān)于偏函數(shù)的定義:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
這是一個(gè)很好的特性,使用bind()我們?cè)O(shè)定函數(shù)的預(yù)定義參數(shù),然后調(diào)用的時(shí)候傳入其他參數(shù)即可:
<script type="text/javascript">
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3);
console.log(list1);// [1, 2, 3]
// 預(yù)定義參數(shù)37
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList();
console.log(list2);// [37]
var list3 = leadingThirtysevenList(1, 2, 3);
console.log(list3);// [37, 1, 2, 3]
</script>
和setTimeout or setInterval一起使用
一般情況下setTimeout()的this指向window或global對(duì)象。當(dāng)使用類的方法時(shí)需要this指向類實(shí)例,就可以使用bind()將this綁定到回調(diào)函數(shù)來(lái)管理實(shí)例。
<script type="text/javascript">
function Bloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// 1秒后調(diào)用declare函數(shù)
Bloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
Bloomer.prototype.declare = function() {
console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};
var test = new Bloomer();
test.bloom();
</script>
綁定函數(shù)作為構(gòu)造函數(shù)
綁定函數(shù)也適用于使用new操作符來(lái)構(gòu)造目標(biāo)函數(shù)的實(shí)例。當(dāng)使用綁定函數(shù)來(lái)構(gòu)造實(shí)例,注意:this會(huì)被忽略,但是傳入的參數(shù)仍然可用。
<script type="text/javascript">
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
console.log(this.x + ',' + this.y);
};
var p = new Point(1, 2);
p.toString(); // 1,2
var YAxisPoint = Point.bind(null,10);
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // 10,5
console.log(axisPoint instanceof Point); // true
console.log(axisPoint instanceof YAxisPoint); // true
console.log(new Point(17, 42) instanceof YAxisPoint); // true
</script>
上面例子中Point和YAxisPoint共享原型,因此使用instanceof運(yùn)算符判斷時(shí)為true
偽數(shù)組的轉(zhuǎn)化
上面的幾個(gè)小節(jié)可以看出bind()有很多的使用場(chǎng)景,但是bind()函數(shù)是在 ECMA-262 第五版才被加入;它可能無(wú)法在所有瀏覽器上運(yùn)行。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了。
首先我們可以通過(guò)給目標(biāo)函數(shù)指定作用域來(lái)簡(jiǎn)單實(shí)現(xiàn)bind()方法:
Function.prototype.bind = function(context){
self = this; //保存this,即調(diào)用bind方法的目標(biāo)函數(shù)
return function(){
return self.apply(context,arguments);
};
};
考慮到函數(shù)柯里化的情況,我們可以構(gòu)建一個(gè)更加健壯的bind():
Function.prototype.bind = function(context){
var args = Array.prototype.slice.call(arguments, 1),
self = this;
return function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply(context,finalArgs);
};<BR>}
這次的bind()方法可以綁定對(duì)象,也支持在綁定的時(shí)候傳參。
繼續(xù),Javascript的函數(shù)還可以作為構(gòu)造函數(shù),那么綁定后的函數(shù)用這種方式調(diào)用時(shí),情況就比較微妙了,需要涉及到原型鏈的傳遞:
Function.prototype.bind = function(context){
var args = Array.prototype.slice(arguments, 1),
F = function(){},
self = this,
bound = function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply((this instanceof F ? this : context), finalArgs);
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
};
這是《JavaScript Web Application》一書(shū)中對(duì)bind()的實(shí)現(xiàn):通過(guò)設(shè)置一個(gè)中轉(zhuǎn)構(gòu)造函數(shù)F,使綁定后的函數(shù)與調(diào)用bind()的函數(shù)處于同一原型鏈上,用new操作符調(diào)用綁定后的函數(shù),返回的對(duì)象也能正常使用instanceof,因此這是最嚴(yán)謹(jǐn)?shù)腷ind()實(shí)現(xiàn)。
對(duì)于為了在瀏覽器中能支持bind()函數(shù),只需要對(duì)上述函數(shù)稍微修改即可:
Function.prototype.bind = function (oThis) {
if (typeof this !== "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 || window,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
以上這篇淺析Javascript中bind()方法的使用與實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
toString.call()通用的判斷數(shù)據(jù)類型方法示例
這篇文章主要給大家介紹了關(guān)于toString.call()通用的判斷數(shù)據(jù)類型方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
v3-admin-vite 整合pont的詳細(xì)過(guò)程
這篇文章主要介紹了v3-admin-vite 整合pont的詳細(xì)過(guò)程,目前后端的Admin模板使用的是v3-admin-vite,需要整合pont接口,方便前后端統(tǒng)一一體化開(kāi)發(fā),本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
JavaScript中利用for循環(huán)遍歷數(shù)組
這篇文章主要為大家詳細(xì)介紹了JavaScript中利用for循環(huán)遍歷數(shù)組,最好不要使用for in遍歷,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
關(guān)于Iframe父頁(yè)面與子頁(yè)面之間的相互調(diào)用
下面小編就為大家?guī)?lái)一篇關(guān)于Iframe父頁(yè)面與子頁(yè)面之間的相互調(diào)用。小編覺(jué)得挺不錯(cuò)的,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧,祝大家游戲愉快哦2016-11-11
判斷目標(biāo)是否是window,document,和擁有tagName的Element的代碼
判斷目標(biāo)是否是window,document,和擁有tagName的Element的代碼,需要的朋友可以參考下。2010-05-05
JavaScript設(shè)計(jì)模式之緩存代理模式原理與簡(jiǎn)單用法示例
這篇文章主要介紹了JavaScript設(shè)計(jì)模式之緩存代理模式原理與簡(jiǎn)單用法,結(jié)合實(shí)例形式簡(jiǎn)要分析了javascript緩存代理模式的基本原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-08-08
JavaScript遍歷求解數(shù)獨(dú)問(wèn)題的主要思路小結(jié)
數(shù)獨(dú)游戲非常流行,其規(guī)則就是1到9數(shù)字填入9*9宮格并要求每一行、每一列、每一個(gè)粗線(小型)宮內(nèi)的數(shù)字不重復(fù),對(duì)此我們來(lái)看一下JavaScript遍歷求解數(shù)獨(dú)問(wèn)題的主要思路小結(jié)2016-06-06
利用Keydown事件阻止用戶輸入實(shí)現(xiàn)代碼
這篇文章主要介紹了利用Keydown事件阻止用戶輸入的具體實(shí)現(xiàn),需要的朋友可以參考下2014-03-03
JavaScript實(shí)現(xiàn)飛舞的泡泡效果
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)飛舞的泡泡效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02

