JS中的bind的实现以及使用
在讨论bind()
方法之前我们先来看一道题目:
var altwrite = document.write;
altwrite("hello");//报错,因为altwrite方法是在window上进行调用的,而window上是没有该方法的
//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(); // var getNum = module.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象 // 创建一个'this'绑定到module的函数
var boundGetNum = getNum.bind(module);
boundGetNum(); //
偏函数(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();
retrun 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;
};
JS中的bind的实现以及使用的更多相关文章
- js中的bind方法的实现方法
js中目前我遇见的改变作用域的5中方法:call, apply, eval, with, bind. var obj = { color: 'green' } function demo () { c ...
- JS中的bind方法学习
EcmaScript5给Function扩展了一个方法:bind 众所周知 在jQuery和prototype.js之类的框架里都有个bind jQuery里的用途是给元素绑定事件 $("# ...
- 理解 backbone.js 中的 bind 和 bindAll 方法,关于如何在方法中指定其中的 this,包含apply方法的说明[转载]
转载自:http://gxxsite.com/content/view/id/132.html 在backbone.js的学习过程中,被bind和bindAll弄得有点晕,这里包括underscore ...
- js中的bind、apply、call、callee、caller的区别
1.bind.apply与call的区别与使用 相同点:2者是函数原型的一个方法,因此调用者都必须是函数,第1个参数都是对象.作用是,用另一个对象替换当前对象,另一对象也即是你传的第一个参数.通常用于 ...
- 分享一个js中的bind方法使用
来源:http://www.cnblogs.com/yuzhongwusan/archive/2012/02/13/2348782.html Js代码 复制代码 代码如下: var first_obj ...
- js 中的bind函数
bind是Function.prototype中内置函数 作用是指定函数作用域 代码参考 http://blog.csdn.net/load_life/article/details/7200381 ...
- JS中的bind 、call 、apply
# 一 .bind 特点: ### 1.返回原函数的拷贝,我们称这个拷贝的函数为绑定函数 ### 2.将函数中的this固定为调用bind方法时的第一个参数,所以称之为绑定函数.注意是名词而非动词. ...
- JS中的bind方法
# bind的机制 ``` var foo = function(){} var bar = foo; console.log(foo === bar) //true /--------------- ...
- 使用另一种方式实现js中Function的调用(call/apply/bind)
在JavaScript中函数的调用可以有多种方式,但更经典的莫过于call和apply.call跟apply都绑定在函数上,他们两个的第一个参数意义相同,传入一个对象,他作为函数的执行环境(实质上是为 ...
随机推荐
- AntData.ORM框架 之DBModel CodeGen如何使用
AntData.ORM 框架 开源地址:https://github.com/yuzd/AntData.ORM 打开VS2015 打开Tools =>Extentions and Updates ...
- 配置NFS服务与tftp服务
在VMware在安装ubuntu的图解 链接:http://pan.baidu.com/s/1jIofvYu 密码:da72 图解里已经解压安装了VMware Tools,接下来必须要安装的就是NFS ...
- 球谐光照(Spherical Harmonics Lighting)及其应用-应用篇
上一篇介绍了球谐函数的一些原理和性质,本篇主要介绍如何实现球谐光照,将这种光照应用到实际的场景中去. 我们知道,球谐光照实际上就是将周围的环境光采样成几个系数,然后渲染的时候用这几个系数来对光照进行还 ...
- HTTP严格安全传输(HTTP Strict Transport Security, HSTS)chromuim实现源码分析(二)
HTTP严格安全传输(HTTP Strict Transport Security, HSTS)chromuim实现源码分析(一) 下面来查看其他对保存HSTS信息的enabled_sts_hosts ...
- 简学Python第四章__装饰器、迭代器、列表生成式
Python第四章__装饰器.迭代器 欢迎加入Linux_Python学习群 群号:478616847 目录: 列表生成式 生成器 迭代器 单层装饰器(无参) 多层装饰器(有参) 冒泡算法 代码开发 ...
- 【转】Jqgrid学习之数据
jqGrid可支持的数据类型:xml.json.jsonp.local or clientSide.xmlstring.jsonstring .script.function (…). Json数据 ...
- HTTP基础知识(一)
一.了解web及网络基础 1.通过发送请求获取服务器资源的web浏览器等的都可称为客户端(client) 2.HTTP:HyperText Transfer Protocol,超文本传输协议:所有的W ...
- Linux 压缩解压及备份命令
linux中压缩与备份命令总结一.压缩与解压缩 1.compress [-rcv] 文件或目录 <==压缩 uncompress 文件.Z <==解压缩 -r:可以连同目录下的文件也同时进 ...
- JavaScript中的函数使用
append() 是代表改变格子的内容 prev()是代表前一个格子 next()是代表下一个相邻的格子 hide()是代表隐藏 show()是代表显示 childen()是代表子节点 eq()是代表 ...
- 使用Github Pages和Hexo构建博客
Github Pages可以创建免费的静态站点,支持自带主题.支持自制页面等,并且可以使用Jekyll或者Hexo等静态博客框架进行管理. 独立博客是博客园等博客平台之外的一个良好补充,相比使用虚拟主 ...