淺析Javascript中bind()方法的使用與實(shí)現(xiàn)
我們先來看一道題目
var write = document.write; write("hello"); //1.以上代碼有什么問題 //2.正確操作是怎樣的
不能正確執(zhí)行,因?yàn)閣rite函數(shù)丟掉了上下文,此時(shí)this的指向global或window對(duì)象,導(dǎo)致執(zhí)行時(shí)提示非法調(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()最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù),使這個(gè)函數(shù)不論怎么調(diào)用都有同樣的this值。常見的錯(cuò)誤就像上面的例子一樣,將方法從對(duì)象中拿出來,然后調(diào)用,并且希望this指向原來的對(duì)象。如果不做特殊處理,一般會(huì)丟失原來的對(duì)象。使用bind()方法能夠很漂亮的解決這個(gè)問題:
<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ù)來管理實(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)造目標(biāo)函數(shù)的實(shí)例。當(dāng)使用綁定函數(shù)來構(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 第五版才被加入;它可能無法在所有瀏覽器上運(yùn)行。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了。
首先我們可以通過給目標(biāo)函數(shù)指定作用域來簡(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》一書中對(duì)bind()的實(shí)現(xiàn):通過設(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)文章
JavaScript面試出現(xiàn)頻繁的一些易錯(cuò)點(diǎn)整理
通過幾個(gè)常見面試開始,討論針對(duì)一個(gè)題目的分析思路,就有了下面這篇文章,本文主要給大家整理總結(jié)介紹了關(guān)于JavaScript面試中會(huì)頻繁出現(xiàn)的一些易錯(cuò)點(diǎn),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起看看吧。2018-03-03javaScript實(shí)現(xiàn)鼠標(biāo)在文字上懸浮時(shí)彈出懸浮層效果
這篇文章主要為大家詳細(xì)介紹了javaScript實(shí)現(xiàn)鼠標(biāo)在文字上懸浮時(shí)彈出懸浮層效果的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03使用JavaScript實(shí)現(xiàn)貪吃蛇游戲
這篇文章主要為大家詳細(xì)介紹了使用JavaScript實(shí)現(xiàn)貪吃蛇游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09Bootstrap 過渡效果Transition 模態(tài)框(Modal)
這篇文章主要介紹了Bootstrap 過渡效果Transition 模態(tài)框(Modal),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03JavaScript?setTimeout和setInterval的用法與區(qū)別詳解
Javascript的setTimeOut和setInterval函數(shù)應(yīng)用非常廣泛,它們都用來處理延時(shí)和定時(shí)任務(wù),下面這篇文章主要給大家介紹了關(guān)于JavaScript?setTimeout和setInterval的用法與區(qū)別,需要的朋友可以參考下2022-04-04javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本
這篇文章主要介紹了javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本的相關(guān)資料,需要的朋友可以參考下2017-02-02JavaScript隨機(jī)打亂數(shù)組順序之隨機(jī)洗牌算法
這篇文章主要介紹了JavaScript隨機(jī)打亂數(shù)組順序之隨機(jī)洗牌算法的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-08-08