javascript中bind函数的作用

javascript的bind的作用

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <style>
 6             button {background-color:#0f0;}
 7         </style>
 8     </head>
 9     <body>
10         <button id="button"> 按钮 </button>
11         <input type="text">
12         <script>
13             var button = document.getElementById("button");
14                 button.onclick = function() {
15                     alert(this.id); // 弹出button
16                 };
17                 //可以看出上下文的this 为button
18         </script>
19     </body>
20 </html>
View Code

此时加入bind

1             var text = document.getElementById("text");
2             var button = document.getElementById("button");
3                 button.onclick = function() {
4                     alert(this.id); // 弹出button
5                 }.bind(text);
6                 //可以看出上下文的this 为button
View Code

此时会发现this改变为text

函数字面量里也适用,目的是保持上下指向(this)不变。

 1 var obj = {
 2             color: "#ccc",        
 3             element: document.getElementById('text'),
 4                     events: function() {
 5                 document.getElementById("button").addEventListener("click", function(e) {
 6                     console.log(this);
 7                 this.element.style.color = this.color;
 8                }.bind(this))
 9         return this;
10     },
11     init: function() {
12         this.events();
13     }
14 };
15    obj.init();
View Code

此时点击按钮text里的字会变色。可见this不为button而是obj。

bind()的方法在ie,6,7,8中不适用,需要扩展通过扩展Function prototype可以实现此方法。

 1  if (!Function.prototype.bind) {
 2 
 3         Function.prototype.bind = function(obj) {
 4             var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function() {
 5             }, bound = function() {
 6                 return self.apply(this instanceof nop ? this : (obj || {}),
 7                         args.concat(slice.call(arguments)));
 8             };
 9 
10             nop.prototype = self.prototype;
11 
12             bound.prototype = new nop();
13 
14             return bound;
15         };
16     }
View Code

此时可以看到ie6,7,8中也支持bind()。

slice = Array.prototype.slice,

array = Array.prototype.slice.call( array, 0 );

将类似数组转换为数组

转载于:https://www.cnblogs.com/mole/p/3994669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值