js的bind方法
转载:http://www.jb51.net/article/94451.htm
http://www.cnblogs.com/TiestoRay/p/3360378.html
https://segmentfault.com/a/1190000002662251
对于函数绑定(Function binding)很有可能是大家在使用JavaScript时最少关注的一点,但是当你意识到你需要一个解决方案来解决如何在另一个函数中保持this上下文的时候,你真正需要的其实就是 Function.prototype.bind() ,只是你有可能仍然没有意识到这点。
第一次遇到这个问题的时候,你可能倾向于将this设置到一个变量上,这样你可以在改变了上下文之后继续引用到它。
一. bind的语法
bind() 方法的主要作用就是将函数绑定至某个对象,bind() 方法会创建一个函数,函数体内this对象的值会被绑定到传入bind() 函数的值。
1.1 定义
bind()的定义如下:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。
1.2 原理
可以用如下代码模拟bind()的原理:
|
1
2
3
4
5
6
|
Function.prototype.bind = function(context) { var self = this; // 保存原函数 return function() { // 返回一个新函数 return self.apply(context, arguments); // 执行新函数时,将传入的上下文context作为新函数的this }} |
1.3 语法
|
1
|
Function.prototype.bind(thisArg[, arg1[, arg2[, ...]]]) |
二. bind的应用场景
2.1 实现对象继承
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
var A = function(name) { this.name = name;}var B = function() { A.bind(this, arguments);}B.prototype.getName = function() { return this.name;}var b = new B("hello");console.log(b.getName()); // "hello" |
2.2 事件处理
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var paint = { color: "red", count: 0, updateCount: function() { this.count++; console.log(this.count); }};// 事件处理函数绑定的错误方法:document.querySelector('button') .addEventListener('click', paint.updateCount); // paint.updateCount函数的this指向变成了该DOM对象// 事件处理函数绑定的正确方法:document.querySelector('button') .addEventListener('click', paint.updateCount.bind(paint)); // paint.updateCount函数的this指向变成了paint |
2.3 时间间隔函数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var notify = { text: "Hello World!", beforeRender: function() { alert(this.text); }, render: function() { // 错误方法: setTimeout(this.beforeRender, 0); // undefined // 正确方法: setTimeout(this.beforeRender.bind(this), 0); // "Hello World!" }};notify.render(); |
2.4 借用Array的原生方法
|
1
2
3
4
|
var a = {};Array.prototype.push.bind(a, "hello", "world")();console.log(a); // "hello", "world" |
三. bind()方法的浏览器兼容性

四. bind()的兼容性写法
|
1
2
3
4
5
6
7
8
9
10
11
12
|
if (!Function.prototype.bind) { Function.prototype.bind = function() { var self = this, // 保存原函数 context = [].shift.call(arguments), // 需要绑定的this上下文 args = [].slice.call(arguments); // 剩余的参数转成数组 return function() { // 返回一个新函数 // 执行新函数时,将传入的上下文context作为新函数的this // 并且组合两次分别传入的参数,作为新函数的参数 return self.apply(context, [].concat.call(args, [].slice.call(arguments))); } };} |
五. bind与 call/apply方法的区别
共同点:
都可以改变函数执行的上下文环境;
不同点:
bind: 不立即执行函数,一般用在异步调用和事件; call/apply: 立即执行函数。
总结
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用Javascript能有一定的帮助,如果有疑问大家可以留言交流。
js的bind方法的更多相关文章
- 【转载】JS中bind方法与函数柯里化
原生bind方法 不同于jQuery中的bind方法只是简单的绑定事件函数,原生js中bind()方法略复杂,该方法上在ES5中被引入,大概就是IE9+等现代浏览器都支持了(有关ES5各项特性的支持情 ...
- 理解js中bind方法的使用
提到bind方法,估计大家还会想到call方法.apply方法:它们都是Function对象内建的方法,它们的第一个参数都是用来更改调用方法中this的指向.需要注意的是bind 是返回新的函数,以便 ...
- JS高级---bind方法的使用
bind方法的使用 //通过对象,调用方法,产生随机数 function ShowRandom() { //1-10的随机数 this.number = parseInt(Math.random() ...
- JS高级---bind方法
bind方法 复制了一份的时候, 把参数传入到了f1函数中, x===>10, y===>20, null就是this, 默认就是window bind方法是复制的意思, 参数可以在复制的 ...
- js实现bind方法
//目标函数 function fun(...args) { console.log(this); console.log(args); } //目标函数原型对象上的一个方法cher func.pro ...
- JS bind()方法、JS原生实现bind()
一.arguments的含义 // arguments 是一个对应于传递给函数的参数的类数组对象 function a(){ console.log(arguments); } a(); // Arg ...
- js中bind解析
一.arguments的含义 // arguments 是一个对应于传递给函数的参数的类数组对象 function a(){ console.log(arguments); } a(); // Arg ...
- js中bind,call,apply方法的应用
最近用js的类写东西,发现一个无比蛋疼的事,那就是封装的类方法中的this指针经常会改变指向,失去上下文,导致程序错误或崩溃. 比如: function Obj(){ this.type = &quo ...
- js学习进阶中-bind()方法
有次面试遇到的,也是没说清楚具体的作用,感觉自己现在还是没有深刻的理解! bind():绑定事件类型和处理函数到DOM element(父元素上) live():绑定事件到根节点上,(document ...
随机推荐
- linux下怎么查看ssh的用户登录日志
linux下登录日志在下面的目录里: cd /var/log 查看ssh用户的登录日志: less secure linux日志管理: 1. 日志简介 日志对于安全来说,非常重要,他记录了系统每天发生 ...
- mysql 远程访问控制
如需要让192.168.2.3的test用户可以访问本机所有数据库,mysql命令如下 mysql>GRANT ALL PRIVILEGES ON *.* TO 'test'@'192.168. ...
- vmware 10 e1000e e1000e_cyclecounter_read 挂机解法
http://ehc.ac/p/e1000/mailman/message/34100875/In the e1000e_cyclecounter_read function, if incvalue ...
- union all 与order by的连用
昨天工作过程中发现一个奇怪的地方: 代码段A: 1---select * from table1 2---order by no 3---union all 4---select * ...
- Simple Infinite automaton [C]
Today I read the book Formal Language and Automaton Theory. And I learnt the infinite automaton. Her ...
- HTML标签----图文详解
国庆节快乐,还在加班的童鞋,良辰必有重谢! 本文主要内容 头标签 排版标签:<p> <br> <hr> <center> ...
- 文件上传&文件下载
一.单个文件上传 文件上传需要两个jar包: 首先制作一个简单的页面,用于实现文件上传 <h1>单个文件上传</h1> <s:form action="uplo ...
- [转]ASP.NET MVC3 + EF 性能优化解决方案以及最优架构
[集思广议] 我们用 asp.net mvc3 + ef 做了一个网站,现在是内测阶段,发现打开速度非常慢.首页打开(无缓存)都在5-6s以上(测试环境:程序和db都在本机),请问各位 mv ...
- 转: Git远程操作详解 (阮一峰)
说明: 通过这个说明终于把远程操作给搞明白了. http://www.ruanyifeng.com/blog/2014/06/git_remote.html
- CSS3文本超出容器显示省略号之text-overflow属性
text-overflow:ellipsis; overflow:hidden; white-space:nowrap; 要想实现文本超出容器时显示省略号,上面3个属性必须同时搭配使用