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

javascriptvar altwrite = document.write;

altwrite("hello");

//1.以上代码有什么问题

//2.正确操作是怎样的

//3.bind()方法怎么实现

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

javascriptaltwrite.bind(document)("hello")

当然也可以使用call()方法:

javascriptaltwrite.call(document, "hello")

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

绑定函数

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

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

javascriptfunction 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绑定到回调函数来管理实例。

javascriptfunction 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会被忽略,但是传入的参数仍然可用。

javascriptfunction 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值的函数创造捷径。

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

javascriptvar slice = Array.prototype.slice;

// ...

slice.call(arguments);

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

javascriptvar unboundSlice = Array.prototype.slice;

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

// ...

slice(arguments);

实现

上面的几个小节可以看出bind()有很多的使用场景,但是bind()函数是在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。这就需要我们自己实现bind()函数了。

首先我们可以通过给目标函数指定作用域来简单实现bind()方法:

javascriptFunction.prototype.bind = function(context){

self = this; //保存this,即调用bind方法的目标函数

return function(){

return self.apply(context,arguments);

};

};

考虑到函数柯里化的情况,我们可以构建一个更加健壮的bind():

javascriptFunction.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的函数还可以作为构造函数,那么绑定后的函数用这种方式调用时,情况就比较微妙了,需要涉及到原型链的传递:

javascriptFunction.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();

retrun bound;

};

这是《JavaScript Web Application》一书中对bind()的实现:通过设置一个中转构造函数F,使绑定后的函数与调用bind()的函数处于同一原型链上,用new操作符调用绑定后的函数,返回的对象也能正常使用instanceof,因此这是最严谨的bind()实现。

对于为了在浏览器中能支持bind()函数,只需要对上述函数稍微修改即可:

javascriptFunction.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;

};

python中bind的用法_Javascript中bind()方法的使用与实现相关推荐

  1. mysql中去重的用法_mysql中去重 distinct 用法

    在使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count( ...

  2. python 字典定义日志用法_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  3. python中max函数用法_Python中max函数用法实例分析

    Python中max函数用法实例分析 更新时间:2015年07月17日 15:45:09 作者:优雅先生 这篇文章主要介绍了Python中max函数用法,实例分析了Python中max函数的功能与使用 ...

  4. python中print的用法_Python中print函数简单使用总结

    Python中print函数简单使用总结 print函数是Python的入门,每一个学习python的人都绕不开这个函数,下面介绍一下这个函数的用法. 打开电脑,选择python软件,下面选择pyth ...

  5. python常用函数的用法_python中常用函数整理

    1.map map是python内置的高阶函数,它接收一个函数和一个列表,函数依次作用在列表的每个元素上,返回一个可迭代map对象. class map(object):""&qu ...

  6. python中lambda()的用法_python中lambda()的用法

    在C++11和C#中都有匿名函数的存在.下面看看在python中匿名函数的使用. 1.lambda只是一个表达式,函数体比def简单很多. 2.lambda的主体是一个表达式,而不是一个代码块.仅仅能 ...

  7. [转载] python里字典的用法_python中字典(Dictionary)用法实例详解

    参考链接: Python字典dictionary copy方法 本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映 ...

  8. python中import math用法_Python math.hypot() 方法

    Python math.hypot() 方法 例如: 找到已知垂直和底角的直角三角形的斜边:#Import math Library import math #垂线与底面 parendicular = ...

  9. python中replace的用法_python中replace的用法是什么?

    python中replace的用法是什么? Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次. r ...

最新文章

  1. Android Architecture Components Part2:LiveData
  2. GAN处理手写图片数据集
  3. 无法卸载_六月累积更新又出问题:打印机故障 部分程序无法打开和卸载
  4. java设计模式在线视频_Java设计模式之单例模式视频课程
  5. 2021年中国大屏幕拼接系统市场趋势报告、技术动态创新及2027年市场预测
  6. 将Vim打造成Python快速开发环境(一)
  7. Zookeeper的Quorum机制-谈谈怎样解决脑裂(split-brain)
  8. Python 文件(文件夹)匹配(glob模块)(转载)
  9. 如何保证API接口数据安全?
  10. pyspark分类算法之逻辑回归模型实践【binomialLogisticRegression+multinomialLogisticRegression】
  11. 恒流源差分放大电路静态分析_第11讲 差分放大电路_清华大学:模拟电子技术基础(华成英)_ppt_大学课件预览_高等教育资讯网...
  12. aspen怎么做灵敏度分析_【技巧篇】Aspen系列篇之——灵敏度分析
  13. 代理服务器的常用端口有哪些?
  14. 常用类(API)第一节
  15. Windows系统中VMWare虚拟机屏幕分辨率调整
  16. 消费者人群画像 python_如何正确打开相似人群画像算法
  17. JavaPOI导出Excel合集——Java导出全内容
  18. 网络加速技术浅析(二)
  19. 蓝牙耳机无法打开计算机,电脑搜不到蓝牙耳机怎么回事_电脑搜不到蓝牙耳机的处理方法【图文】...
  20. unity怎么显示骨骼_Unity骨骼动画的总结

热门文章

  1. 存量客户管理之提额降息
  2. 从零开始的前端异次元生活
  3. Luogu4725 【模板】多项式对数函数(NTT+多项式求逆)
  4. android - 调用系统分享功能分享图片
  5. visio转换成eps
  6. 24.Linux-Nand Flash驱动(分析MTD层并制作NAND驱动)
  7. CentOS6 安装Sendmail + Dovecot + Squirrelmail
  8. 【模板】prim的heap优化
  9. C++STL-priority_queue
  10. IBAction和IBOutlet