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


Posted in Javascript onApril 29, 2016

在讨论bind()方法之前我们先来看一道题目:

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

对于上面这道题目,答案并不是太难,主要考点就是this指向的问题,altwrite()函数改变this的指向global或window对象,导致执行时提示非法调用异常,正确的方案就是使用bind()方法:

altwrite.bind(document)("hello") 
当然也可以使用call()方法:

altwrite.call(document, "hello") 
本文的重点在于讨论第三个问题bind()方法的实现,在开始讨论bind()的实现之前,我们先来看看bind()方法的使用:

绑定函数
bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。常见的错误就像上面的例子一样,将方法从对象中拿出来,然后调用,并且希望this指向原来的对象。如果不做特殊处理,一般会丢失原来的对象。使用bind()方法能够很漂亮的解决这个问题:

this.num = 9; 
var mymodule = { 
 num: 81,
 getNum: function() { return this.num; }
};

module.getNum(); // 81

var getNum = module.getNum; 
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

// 创建一个'this'绑定到module的函数
var boundGetNum = getNum.bind(module); 
boundGetNum(); // 81

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

function list() { 
 return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 预定义参数37
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37] 
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

和setTimeout一起使用

一般情况下setTimeout()的this指向window或global对象。当使用类的方法时需要this指向类实例,就可以使用bind()将this绑定到回调函数来管理实例。

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 + ' 朵花瓣!');
};

注意:对于事件处理函数和setInterval方法也可以使用上面的方法

绑定函数作为构造函数

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

function Point(x, y) { 
 this.x = x;
 this.y = y;
}

Point.prototype.toString = function() { 
 return this.x + ',' + this.y; 
};

var p = new Point(1, 2); 
p.toString(); // '1,2'


var emptyObj = {}; 
var YAxisPoint = Point.bind(emptyObj, 0/*x*/); 
// 实现中的例子不支持,
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);

var axisPoint = new YAxisPoint(5); 
axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true 
axisPoint instanceof YAxisPoint; // true 
new Point(17, 42) instanceof YAxisPoint; // true

上面例子中Point和YAxisPoint共享原型,因此使用instanceof运算符判断时为true。

捷径

bind()也可以为需要特定this值的函数创造捷径。

例如要将一个类数组对象转换为真正的数组,可能的例子如下:

var slice = Array.prototype.slice;

// ...

slice.call(arguments);

如果使用bind()的话,情况变得更简单:

var unboundSlice = Array.prototype.slice; 
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);

实现

上面的几个小节可以看出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);
 };
};

这次的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 图片延迟加载并等比缩放插件
Nov 09 Javascript
js setTimeout 常见问题小结
Aug 13 Javascript
简单时间提示DEMO从0开始一直进行计时
Nov 19 Javascript
JS实现简单的tab切换选项卡效果
Sep 21 Javascript
React.js中常用的ES6写法总结(推荐)
May 09 Javascript
vue.js通过路由实现经典的三栏布局实例代码
Jul 08 Javascript
vue中利用Promise封装jsonp并调取数据
Jun 18 Javascript
Vue 页面权限控制和登陆验证功能的实例代码
Jun 20 Javascript
在vue项目中使用sass语法问题
Jul 18 Javascript
JavaScript的查询机制LHS和RHS解析
Aug 16 Javascript
jQuery实现验证用户登录
Dec 10 jQuery
selenium 反爬虫之跳过淘宝滑块验证功能的实现代码
Aug 27 Javascript
深入剖析JavaScript中的函数currying柯里化
Apr 29 #Javascript
javascript中利用柯里化函数实现bind方法【推荐】
Apr 29 #Javascript
jQuery Ajax 实例代码 ($.ajax、$.post、$.get)
Apr 29 #Javascript
一个字符串中出现次数最多的字符 统计这个次数【实现代码】
Apr 29 #Javascript
JS弹出层遮罩,隐藏背景页面滚动条细节优化分析
Apr 29 #Javascript
老生常谈遮罩层 滚动条的问题
Apr 29 #Javascript
弹出遮罩层后禁止滚动效果【实现代码】
Apr 29 #Javascript
You might like
从PHP的源码中深入了解stdClass类
2014/04/18 PHP
php使用curl获取https请求的方法
2015/02/11 PHP
div移动 输入框不能输入的问题
2009/11/19 Javascript
Js 时间间隔计算的函数(间隔天数)
2011/11/15 Javascript
AngularJS入门教程(一):静态模板
2014/12/06 Javascript
移动设备web开发首选框架:zeptojs介绍
2015/01/29 Javascript
jquery马赛克拼接翻转效果代码分享
2015/08/24 Javascript
Bootstrap编写一个同时适用于PC、平板、手机的登陆页面
2016/06/30 Javascript
实例分析nodejs模块xml2js解析xml过程中遇到的坑
2017/03/18 NodeJs
jQuery实现点击DIV同时点击CheckBox,并为DIV上背景色的实例
2017/12/18 jQuery
详解Javascript 中的 class、构造函数、工厂函数
2017/12/20 Javascript
jQuery实现的上传图片本地预览效果简单示例
2018/03/29 jQuery
JS返回页面时自动回滚到历史浏览位置
2018/09/26 Javascript
JS/jQuery实现获取时间的方法及常用类完整示例
2019/03/07 jQuery
javaScript把其它类型转换为Number类型
2019/10/13 Javascript
jQuery操作动画完整实例分析
2020/01/10 jQuery
[01:32]2016国际邀请赛中国区预选赛CDEC战队教练采访
2016/06/26 DOTA
[05:15]2018年度CS GO社区贡献奖-完美盛典
2018/12/16 DOTA
Python实现全角半角转换的方法
2014/08/18 Python
Python lxml模块安装教程
2015/06/02 Python
简介Python的collections模块中defaultdict类型的用法
2016/07/07 Python
Python实现Sqlite将字段当做索引进行查询的方法
2016/07/21 Python
Python实现Linux的find命令实例分享
2017/06/04 Python
Python装饰器用法实例总结
2018/02/07 Python
python使用Paramiko模块实现远程文件拷贝
2019/04/30 Python
python如何将两张图片生成为全景图片
2020/03/05 Python
编写一个类体现构造,公有,私有方法,静态,私有变量
2013/08/10 面试题
保密工作实施方案
2014/02/24 职场文书
父亲节活动策划方案
2014/08/24 职场文书
医疗专业毕业生求职信
2014/08/28 职场文书
2014最新股权信托合同协议书
2014/11/18 职场文书
工程部经理岗位职责
2015/02/02 职场文书
中学生国庆节演讲稿2015
2015/07/30 职场文书
如何书写民事调解协议书?
2019/06/25 职场文书
数据分析数据库ClickHouse在大数据领域应用实践
2022/04/03 MySQL
SQL Server一个字符串拆分多行显示或者多行数据合并成一个字符串
2022/05/25 SQL Server