浅析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为搜索栏增加tag提示
Jun 22 Javascript
javascript打印html内容功能的方法示例
Nov 28 Javascript
Jquery的基本对象转换和文档加载用法实例
Feb 25 Javascript
jQuery实现的手机发送验证码倒计时效果代码分享
Aug 24 Javascript
jquery实现在网页指定区域显示自定义右键菜单效果
Aug 25 Javascript
使用jquery.form.js实现图片上传的方法
May 05 Javascript
JQuery点击行tr实现checkBox选中的简单实例
May 26 Javascript
基于Vue如何封装分页组件
Dec 16 Javascript
bootstrap table插件的分页与checkbox使用详解
Jul 23 Javascript
微信小程序网络层封装的实现(promise, 登录锁)
May 08 Javascript
Vue请求java服务端并返回数据代码实例
Nov 28 Javascript
Angular8 实现table表格表头固定效果
Jan 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简洁函数小结
2011/08/12 PHP
php在程序中将网页生成word文档并提供下载的代码
2012/10/09 PHP
php常见的魔术方法详解
2014/12/25 PHP
PHP使用Curl实现模拟登录及抓取数据功能示例
2018/04/27 PHP
PHP PDOStatement::errorCode讲解
2019/01/31 PHP
HR vs CL BO3 第一场 2.13
2021/03/10 DOTA
JS 参数传递的实际应用代码分析
2009/09/13 Javascript
JS中setInterval、setTimeout不能传递带参数的函数的解决方案
2013/04/28 Javascript
js算法中的排序、数组去重详细概述
2013/10/14 Javascript
JavaScript 语言基础知识点总结(思维导图)
2013/11/10 Javascript
jQuery EasyUI之DataGrid使用实例详解
2016/01/04 Javascript
AngularJs基本特性解析(一)
2016/07/21 Javascript
window.open打开窗口被拦截的快速解决方法
2016/08/04 Javascript
AngularJS  $modal弹出框实例代码
2016/08/24 Javascript
React Native中的RefreshContorl下拉刷新使用
2017/10/09 Javascript
JS实现可控制的进度条
2020/03/25 Javascript
[53:50]CHAOS vs Mineski 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/18 DOTA
Python中return语句用法实例分析
2015/08/04 Python
Python基础中所出现的异常报错总结
2016/11/19 Python
django启动uwsgi报错的解决方法
2018/04/08 Python
python requests证书问题解决
2019/09/05 Python
Python 线程池用法简单示例
2019/10/02 Python
Python将列表中的元素转化为数字并排序的示例
2019/12/25 Python
Python的赋值、深拷贝与浅拷贝的区别详解
2020/02/12 Python
Python编程快速上手——疯狂填词程序实现方法分析
2020/02/29 Python
Django 实现对已存在的model进行更改
2020/03/28 Python
python解包用法详解
2021/02/17 Python
女装和独特珠宝:Sundance Catalog
2018/09/19 全球购物
英国领先的高级美容和在线皮肤诊所:Face the Future
2020/06/17 全球购物
新闻专业个人自我评价
2013/09/21 职场文书
升职自荐书范文
2013/11/28 职场文书
党课心得体会范文
2014/09/09 职场文书
2014党员批评和自我批评思想汇报
2014/09/21 职场文书
骨干教师个人总结
2015/02/11 职场文书
学雷锋广播稿大全
2015/08/19 职场文书
Go中使用gjson来操作JSON数据的实现
2022/08/14 Golang