淺析Javascript中bind()方法的使用與實現(xiàn)
我們先來看一道題目
var write = document.write;
write("hello");
//1.以上代碼有什么問題
//2.正確操作是怎樣的
不能正確執(zhí)行,因為write函數(shù)丟掉了上下文,此時this的指向global或window對象,導(dǎo)致執(zhí)行時提示非法調(diào)用異常,所以我們需要改變this的指向
正確的方案就是使用 bind/call/apply來改變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()最簡單的用法是創(chuàng)建一個函數(shù),使這個函數(shù)不論怎么調(diào)用都有同樣的this值。常見的錯誤就像上面的例子一樣,將方法從對象中拿出來,然后調(diào)用,并且希望this指向原來的對象。如果不做特殊處理,一般會丟失原來的對象。使用bind()方法能夠很漂亮的解決這個問題:
<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.
這是一個很好的特性,使用bind()我們設(shè)定函數(shù)的預(yù)定義參數(shù),然后調(diào)用的時候傳入其他參數(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對象。當(dāng)使用類的方法時需要this指向類實例,就可以使用bind()將this綁定到回調(diào)函數(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操作符來構(gòu)造目標函數(shù)的實例。當(dāng)使用綁定函數(shù)來構(gòu)造實例,注意:this會被忽略,但是傳入的參數(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運算符判斷時為true
偽數(shù)組的轉(zhuǎn)化
上面的幾個小節(jié)可以看出bind()有很多的使用場景,但是bind()函數(shù)是在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運行。這就需要我們自己實現(xiàn)bind()函數(shù)了。
首先我們可以通過給目標函數(shù)指定作用域來簡單實現(xiàn)bind()方法:
Function.prototype.bind = function(context){
self = this; //保存this,即調(diào)用bind方法的目標函數(shù)
return function(){
return self.apply(context,arguments);
};
};
考慮到函數(shù)柯里化的情況,我們可以構(gòu)建一個更加健壯的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()方法可以綁定對象,也支持在綁定的時候傳參。
繼續(xù),Javascript的函數(shù)還可以作為構(gòu)造函數(shù),那么綁定后的函數(shù)用這種方式調(diào)用時,情況就比較微妙了,需要涉及到原型鏈的傳遞:
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》一書中對bind()的實現(xiàn):通過設(shè)置一個中轉(zhuǎn)構(gòu)造函數(shù)F,使綁定后的函數(shù)與調(diào)用bind()的函數(shù)處于同一原型鏈上,用new操作符調(diào)用綁定后的函數(shù),返回的對象也能正常使用instanceof,因此這是最嚴謹?shù)腷ind()實現(xiàn)。
對于為了在瀏覽器中能支持bind()函數(shù),只需要對上述函數(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()方法的使用與實現(xiàn)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript面試出現(xiàn)頻繁的一些易錯點整理
通過幾個常見面試開始,討論針對一個題目的分析思路,就有了下面這篇文章,本文主要給大家整理總結(jié)介紹了關(guān)于JavaScript面試中會頻繁出現(xiàn)的一些易錯點,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起看看吧。2018-03-03
javaScript實現(xiàn)鼠標在文字上懸浮時彈出懸浮層效果
這篇文章主要為大家詳細介紹了javaScript實現(xiàn)鼠標在文字上懸浮時彈出懸浮層效果的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Bootstrap 過渡效果Transition 模態(tài)框(Modal)
這篇文章主要介紹了Bootstrap 過渡效果Transition 模態(tài)框(Modal),非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03
JavaScript?setTimeout和setInterval的用法與區(qū)別詳解
Javascript的setTimeOut和setInterval函數(shù)應(yīng)用非常廣泛,它們都用來處理延時和定時任務(wù),下面這篇文章主要給大家介紹了關(guān)于JavaScript?setTimeout和setInterval的用法與區(qū)別,需要的朋友可以參考下2022-04-04
javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本
這篇文章主要介紹了javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本的相關(guān)資料,需要的朋友可以參考下2017-02-02
JavaScript隨機打亂數(shù)組順序之隨機洗牌算法
這篇文章主要介紹了JavaScript隨機打亂數(shù)組順序之隨機洗牌算法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08

