浅析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删除数组元素的函数介绍
Mar 27 Javascript
PHP+mysql+Highcharts生成饼状图
May 04 Javascript
使用JavaScript的AngularJS库编写hello world的方法
Jun 23 Javascript
基于jquery实现省市联动效果
Nov 23 Javascript
js+css实现select的美化效果
Mar 24 Javascript
jQuery如何防止Ajax重复提交
Oct 14 Javascript
详解如何使用webpack在vue项目中写jsx语法
Nov 08 Javascript
jquery实现侧边栏左右伸缩效果的示例
Dec 19 jQuery
Swiper 4.x 使用方法(移动端网站的内容触摸滑动)
May 17 Javascript
浅谈express.js框架中间件(middleware)
Apr 07 Javascript
手把手教你 CKEDITOR 4 实现Dialog 内嵌 IFrame操作详解
Jun 18 Javascript
vue项目中企业微信使用js-sdk时config和agentConfig配置方式详解
Dec 15 Vue.js
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的5个入手程序
2006/11/23 PHP
php 动态执行带有参数的类方法
2009/04/10 PHP
php 常用类汇总 推荐收藏
2010/05/13 PHP
php实现查看邮件是否已被阅读的方法
2013/12/03 PHP
php缩放gif和png图透明背景变成黑色的解决方法
2014/10/14 PHP
laravel安装和配置教程
2014/10/29 PHP
PHP图像处理之imagecreate、imagedestroy函数介绍
2014/11/19 PHP
laravel 5 实现模板主题功能
2015/03/02 PHP
PHP关联数组实现根据元素值删除元素的方法
2015/06/26 PHP
php发送短信验证码完成注册功能
2015/11/24 PHP
js特殊字符转义介绍
2013/11/05 Javascript
JS中的log对象获取以及debug的写法介绍
2014/03/03 Javascript
js图片实时加载提供网页打开速度
2014/09/11 Javascript
详谈JavaScript内存泄漏
2014/11/14 Javascript
IE8兼容Jquery.validate.js的问题
2016/12/01 Javascript
原生js实现获取form表单数据代码实例
2019/03/27 Javascript
vue路由--网站导航功能详解
2019/03/29 Javascript
jquery实现二级导航下拉菜单效果实例
2019/05/14 jQuery
vue中typescript装饰器的使用方法超实用教程
2019/06/17 Javascript
关于vue3默认把所有onSomething当作v-on事件绑定的思考
2020/05/15 Javascript
vue 解决在微信内置浏览器中调用支付宝支付的情况
2020/11/09 Javascript
微信小程序自定义胶囊样式
2020/12/27 Javascript
使用IronPython把Python脚本集成到.NET程序中的教程
2015/03/31 Python
pandas获取groupby分组里最大值所在的行方法
2018/04/20 Python
对Django 转发和重定向的实例详解
2019/08/06 Python
为什么说Python可以实现所有的算法
2019/10/04 Python
如何解决python多种版本冲突问题
2020/10/13 Python
基于DOM+CSS3实现OrgChart组织结构图插件
2016/03/02 HTML / CSS
乌克兰时尚鞋子和衣服购物网站:Born2be
2018/05/24 全球购物
微软台湾官方网站:Microsoft台湾
2018/08/15 全球购物
servlet面试题
2012/08/20 面试题
机关单位人员学雷锋心得体会
2014/03/10 职场文书
四查四看自我剖析材料
2014/09/19 职场文书
英文感谢信范文
2015/01/21 职场文书
横店影视城导游词
2015/02/06 职场文书
实用求职信模板范文
2019/05/13 职场文书