浅析Javascript中bind()方法的使用与实现


Posted in Javascript onMay 30, 2016

我们先来看一道题目

var write = document.write;  
write("hello");  
//1.以上代码有什么问题 
//2.正确操作是怎样的

不能正确执行,因为write函数丢掉了上下文,此时this的指向global或window对象,导致执行时提示非法调用异常,所以我们需要改变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函数

bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。常见的错误就像上面的例子一样,将方法从对象中拿出来,然后调用,并且希望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>

偏函数(Partial Functions)

Partial Functions也叫Partial Applications,这里截取一段关于偏函数的定义:

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()我们设定函数的预定义参数,然后调用的时候传入其他参数即可:

<script type="text/javascript"> 
 
function list() {  
 return Array.prototype.slice.call(arguments); 
} 
 
var list1 = list(1, 2, 3); 
console.log(list1);// [1, 2, 3] 
 
// 预定义参数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对象。当使用类的方法时需要this指向类实例,就可以使用bind()将this绑定到回调函数来管理实例。

<script type="text/javascript"> 
 
function Bloomer() {  
 this.petalCount = Math.ceil(Math.random() * 12) + 1; 
} 
 
// 1秒后调用declare函数 
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>

绑定函数作为构造函数

绑定函数也适用于使用new操作符来构造目标函数的实例。当使用绑定函数来构造实例,注意:this会被忽略,但是传入的参数仍然可用。

 

<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

伪数组的转化

上面的几个小节可以看出bind()有很多的使用场景,但是bind()函数是在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。这就需要我们自己实现bind()函数了。

首先我们可以通过给目标函数指定作用域来简单实现bind()方法:

Function.prototype.bind = function(context){  
 self = this; //保存this,即调用bind方法的目标函数 
 return function(){ 
   return self.apply(context,arguments); 
 }; 
};

考虑到函数柯里化的情况,我们可以构建一个更加健壮的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()方法可以绑定对象,也支持在绑定的时候传参。

继续,Javascript的函数还可以作为构造函数,那么绑定后的函数用这种方式调用时,情况就比较微妙了,需要涉及到原型链的传递:

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()的实现:通过设置一个中转构造函数F,使绑定后的函数与调用bind()的函数处于同一原型链上,用new操作符调用绑定后的函数,返回的对象也能正常使用instanceof,因此这是最严谨的bind()实现。

对于为了在浏览器中能支持bind()函数,只需要对上述函数稍微修改即可:

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()方法的使用与实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JS限制上传图片大小不使用控件在本地实现
Dec 19 Javascript
jQuery中eq()方法用法实例
Jan 05 Javascript
jQuery EasyUI学习教程之datagrid点击列表头排序
Jul 09 Javascript
jquery轮播的实现方式 附完整实例
Jul 28 Javascript
Vue.js 2.0 移动端拍照压缩图片上传预览功能
Mar 06 Javascript
浅谈js-FCC算法Friendly Date Ranges(详解)
Apr 10 Javascript
angular.js实现列表orderby排序的方法
Oct 02 Javascript
小程序如何使用分包加载的实现方法
May 22 Javascript
简单了解JavaScript中的执行上下文和堆栈
Jun 24 Javascript
ES6 Array常用扩展的应用实例分析
Jun 26 Javascript
react 移动端实现列表左滑删除的示例代码
Jul 04 Javascript
react 生命周期实例分析
May 18 Javascript
Bootstrap Paginator分页插件使用方法详解
May 30 #Javascript
深入理解JavaScript中的call、apply、bind方法的区别
May 30 #Javascript
全面解析Bootstrap中transition、affix的使用方法
May 30 #Javascript
全面解析Bootstrap中form、navbar的使用方法
May 30 #Javascript
js实现页面a向页面b传参的方法
May 29 #Javascript
浅析jQuery中使用$所引发的问题
May 29 #Javascript
基于jQuery实现仿百度首页选项卡切换效果
May 29 #Javascript
You might like
php设计模式 Strategy(策略模式)
2011/06/26 PHP
PHP设计模式之装饰者模式
2012/02/29 PHP
解析如何修改phpmyadmin中的默认登陆超时时间
2013/06/25 PHP
php使用正则表达式提取字符串中尖括号、小括号、中括号、大括号中的字符串
2020/04/05 PHP
PHP连接和操作MySQL数据库基础教程
2014/09/29 PHP
php计算2个日期的差值函数分享
2015/02/02 PHP
PHP使用正则表达式实现过滤非法字符串功能示例
2018/06/04 PHP
PHP高并发和大流量解决方案整理
2021/03/09 PHP
js函数般调用正则
2008/04/08 Javascript
JAVASCRIPT车架号识别/验证函数代码 汽车车架号验证程序
2012/01/08 Javascript
关于jquery的多个选择器的使用示例
2013/10/18 Javascript
js实现带搜索功能的下拉框实时搜索实时匹配
2013/11/05 Javascript
图片上传插件jquery.uploadify详解
2013/11/15 Javascript
简介JavaScript中POSITIVE_INFINITY值的使用
2015/06/05 Javascript
Node.js Streams文件读写操作详解
2016/07/04 Javascript
vue数据双向绑定原理解析(get &amp; set)
2017/03/08 Javascript
ES6正则的扩展实例详解
2017/04/25 Javascript
Vue中封装input组件的实例详解
2017/10/17 Javascript
详解Python3.1版本带来的核心变化
2015/04/07 Python
在Django的form中使用CSS进行设计的方法
2015/07/18 Python
Python图像处理实现两幅图像合成一幅图像的方法【测试可用】
2019/01/04 Python
PyQt5+requests实现车票查询工具
2019/01/21 Python
python实现扑克牌交互式界面发牌程序
2020/04/22 Python
html5小技巧之通过document.head获取head元素
2014/06/04 HTML / CSS
海信商城:海信电视、科龙空调、容声冰箱官方专卖
2017/02/07 全球购物
什么叫应用程序域?什么是受管制的代码?什么是强类型系统?什么是装箱和拆箱?
2016/08/13 面试题
Linux如何压缩可执行文件
2014/03/27 面试题
2014基层党员干部学习全国两会心得体会
2014/03/17 职场文书
考试作弊检讨书1000字(5篇)
2014/10/19 职场文书
高校教师个人工作总结2014
2014/12/17 职场文书
特此通知格式
2015/04/27 职场文书
升学宴家长答谢词
2015/09/29 职场文书
教你使用Pandas直接核算Excel中快递费用
2021/05/12 Python
了解Redis常见应用场景
2021/06/23 Redis
Mysql binlog日志文件过大的解决
2021/10/05 MySQL