浅析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 相关文章推荐
Jquery刷新页面背景图片随机变换的实现方法
Mar 15 Javascript
Javascript MVC框架Backbone.js详解
Sep 18 Javascript
js实现class样式的修改、添加及删除的方法
Jan 20 Javascript
javascript基本包装类型介绍
Apr 10 Javascript
JavaScript拖拽、碰撞、重力及弹性运动实例分析
Jan 08 Javascript
微信公众号  提示:Unauthorized API function 问题解决方法
Dec 05 Javascript
ES6学习笔记之map、set与数组、对象的对比
Mar 01 Javascript
vue-cli 组件的导入与使用教程详解
Apr 11 Javascript
浅谈Vue数据响应
Nov 05 Javascript
JavaScript 性能提升之路(推荐)
Apr 10 Javascript
vue实现歌手列表字母排序下拉滚动条侧栏排序实时更新
May 14 Javascript
mpvue网易云短信接口实现小程序短信登录的示例代码
Apr 03 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函数method_exists()与is_callable()的区别
2013/06/21 PHP
laravel框架实现去掉URL中index.php的方法
2019/10/12 PHP
jscript之List Excel Color Values
2007/06/13 Javascript
javascript function调用时的参数检测常用办法
2010/02/26 Javascript
javascript学习笔记(十八) 获得页面中的元素代码
2012/06/20 Javascript
『JavaScript』限制Input只能输入数字实现思路及代码
2013/04/22 Javascript
JS判断不能为空实例代码
2013/11/26 Javascript
js跨域请求的5中解决方式
2015/07/02 Javascript
JavaScript使用encodeURI()和decodeURI()获取字符串值的方法
2015/08/04 Javascript
jQuery实现Flash效果上下翻动的中英文导航菜单代码
2015/09/22 Javascript
js实现n秒倒计时后才可以点击的效果
2015/12/20 Javascript
分享jQuery插件的学习笔记
2016/01/14 Javascript
TinyMCE汉化及本地上传图片功能实例详解
2016/05/31 Javascript
NodeJs测试框架Mocha的安装与使用
2017/03/28 NodeJs
Angular.js中ng-include用法及多标签页面的实现方式详解
2017/05/07 Javascript
vue router嵌套路由在history模式下刷新无法渲染页面问题的解决方法
2018/01/25 Javascript
js+canvas实现滑动拼图验证码功能
2018/03/26 Javascript
详解webpack模块加载器兼打包工具
2018/09/11 Javascript
video.js 一个页面同时播放多个视频的实例代码
2018/11/27 Javascript
JS实现图片轮播效果实例详解【可自动和手动】
2019/04/04 Javascript
vue从零实现一个消息通知组件的方法详解
2020/03/16 Javascript
python基本语法练习实例
2017/09/19 Python
Python中类的初始化特殊方法
2017/12/01 Python
将tensorflow的ckpt模型存储为npy的实例
2018/07/09 Python
Django CSRF跨站请求伪造防护过程解析
2019/07/31 Python
浅谈pytorch torch.backends.cudnn设置作用
2020/02/20 Python
基于Python快速处理PDF表格数据
2020/06/03 Python
类如何去实现接口
2013/12/19 面试题
信息部岗位职责
2013/11/12 职场文书
测量工程专业求职信
2014/02/24 职场文书
美容院营销方案
2014/03/05 职场文书
不错的求职信范文
2014/07/20 职场文书
2014年科协工作总结
2014/12/09 职场文书
三峡大坝导游词
2015/01/31 职场文书
公司年会开场白
2015/06/01 职场文书
Python使用pandas导入xlsx格式的excel文件内容操作代码
2022/12/24 Python