网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 javascript中bind函数的作用实例介绍
内容
    1234567891011121314151617181920 <!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)不变。
    ?123456789101112131415 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可以实现此方法。
    ?12345678910111213141516 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 );
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/22 14:04:01