javascript中bind函数的作用实例介绍
来源:易贤网 阅读:419 次 日期:2016-06-30 09:20:56
温馨提示:易贤网小编为您整理了“javascript中bind函数的作用实例介绍”,方便广大网友查阅!

<!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函数的作用实例介绍
由于各方面情况的不断调整与变化,易贤网提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!
关于我们 | 联系我们 | 人才招聘 | 网站声明 | 网站帮助 | 非正式的简要咨询 | 简要咨询须知 | 加入群交流 | 手机站点 | 投诉建议
工业和信息化部备案号:滇ICP备2023014141号-1 云南省教育厅备案号:云教ICP备0901021 滇公网安备53010202001879号 人力资源服务许可证:(云)人服证字(2023)第0102001523号
云南网警备案专用图标
联系电话:0871-65317125(9:00—18:00) 获取招聘考试信息及咨询关注公众号:hfpxwx
咨询QQ:526150442(9:00—18:00)版权所有:易贤网
云南网警报警专用图标