浅析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 相关文章推荐
ext jquery 简单比较
Apr 07 Javascript
dojo随手记 gird组件引用
Feb 24 Javascript
使用script的src实现跨域和类似ajax效果
Nov 10 Javascript
学习JavaScript设计模式之责任链模式
Jan 18 Javascript
纯JS实现可拖拽表单的简单实例
Sep 02 Javascript
Angular下H5上传图片的方法(可多张上传)
Jan 09 Javascript
react-router实现跳转传值的方法示例
May 27 Javascript
浅析JS中常用类型转换及运算符表达式
Jul 23 Javascript
jQuery实现的点击图片居中放大缩小功能示例
Jan 16 jQuery
layer ui插件显示tips时,修改字体颜色的实现方法
Sep 11 Javascript
小程序实现tab标签页
Nov 16 Javascript
node.js使用express-fileupload中间件实现文件上传
Jul 16 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中的 == 运算符进行字符串比较
2006/11/26 PHP
PHP基于imap获取邮件实例
2014/11/11 PHP
PHP针对JSON操作实例分析
2015/01/12 PHP
PHP实现redis限制单ip、单用户的访问次数功能示例
2018/06/16 PHP
php实现通过stomp协议连接ActiveMQ操作示例
2020/02/23 PHP
JQuery 学习笔记01 JQuery初接触
2010/05/06 Javascript
javascript 全选与全取消功能的实现代码
2012/12/23 Javascript
JS远程获取网页源代码实例
2013/09/05 Javascript
jQuery aminate方法定位到页面具体位置
2013/12/26 Javascript
让input框实现类似百度的搜索提示(基于jquery事件监听)
2014/01/31 Javascript
Javascript中Array.prototype.map()详解
2014/10/22 Javascript
jQuery判断指定id的对象是否存在的方法
2015/05/22 Javascript
Javascript简写条件语句(推荐)
2016/06/12 Javascript
Bootstrap下拉菜单效果实例代码分享
2016/06/30 Javascript
jQuery Ajax 异步加载显示等待效果代码分享
2016/08/01 Javascript
jquery实时获取时间的简单实例
2017/01/26 Javascript
Bootstrap BootstrapDialog使用详解
2017/02/17 Javascript
JS实现合并json对象的方法
2017/10/10 Javascript
vue.js 获取select中的value实例
2018/03/01 Javascript
简单的React SSR服务器渲染实现
2018/12/11 Javascript
详解ECMAScript2019/ES10新属性
2019/12/06 Javascript
解决vue bus.$emit触发第一次$on监听不到问题
2020/07/28 Javascript
解决vue项目axios每次请求session不一致的问题
2020/10/24 Javascript
在vue中使用image-webpack-loader实例
2020/11/12 Javascript
Python之str操作方法(详解)
2017/06/19 Python
python自动重试第三方包retrying模块的方法
2018/04/24 Python
浅谈Python3 numpy.ptp()最大值与最小值的差
2019/08/24 Python
如何利用Python给自己的头像加一个小国旗(小月饼)
2020/10/02 Python
使用Pytorch搭建模型的步骤
2020/11/16 Python
详解Python openpyxl库的基本应用
2021/02/26 Python
Html5 页面适配iPhoneX(就是那么简单)
2019/09/05 HTML / CSS
加拿大在线隐形眼镜和眼镜店:VisionPros
2019/10/06 全球购物
质检员的岗位职责
2013/11/15 职场文书
个人三严三实对照检查材料
2014/09/25 职场文书
董事长岗位职责
2015/02/13 职场文书
卫生院义诊活动总结
2015/05/07 职场文书