手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >javascript中bind函数的作用实例介绍
javascript中bind函数的作用实例介绍
摘要:button{background-color:#0f0;}按钮varbutton=document.getElementById("but...

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> button {background-color:#0f0;} </style> </head> <body> <button id="button"> 按钮 </button> <input type="text"> <script> var button = document.getElementById("button"); button.onclick = function() { alert(this.id); // 弹出button }; //可以看出上下文的this 为button </script> </body> </html>

此时加入bind

复制代码 代码如下:

var text = document.getElementById("text");

var button = document.getElementById("button");

button.onclick = function() {

alert(this.id); // 弹出button

}.bind(text);

//可以看出上下文的this 为button

此时会发现this改变为text

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

var obj = { color: "#ccc", element: document.getElementById('text'), events: function() { document.getElementById("button").addEventListener("click", function(e) { console.log(this); this.element.style.color = this.color; }.bind(this)) return this; }, init: function() { this.events(); } }; obj.init();

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

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

if (!Function.prototype.bind) { Function.prototype.bind = function(obj) { var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function() { }, bound = function() { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))); }; nop.prototype = self.prototype; bound.prototype = new nop(); return bound; }; }

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

复制代码 代码如下:

slice = Array.prototype.slice,

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

将类似数组转换为数组

【javascript中bind函数的作用实例介绍】相关文章:

JavaScript基本数据结构

JavaSacript中charCodeAt()方法的使用详解

详解JavaScript中的表单验证

详解JavaScript中setSeconds()方法的使用

javascript组合使用构造函数模式和原型模式实例

Javascript实现div的toggle效果实例分析

javascript委托(Delegate)blur和focus用法实例分析

javascript去除空格方法小结

JavaScript中String.match()方法的使用详解

Javascript节点关系实例分析

精品推荐
分类导航