javascript中bind函數的作用實例介紹
來源:易賢網 閱讀:1071 次 日期:2014-09-29 11:13:30
溫馨提示:易賢網小編為您整理了“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里的字會變色??梢妕his不為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 );

更多信息請查看IT技術專欄

更多信息請查看腳本欄目
易賢網手機網站地址:javascript中bind函數的作用實例介紹
由于各方面情況的不斷調整與變化,易賢網提供的所有考試信息和咨詢回復僅供參考,敬請考生以權威部門公布的正式信息和咨詢為準!

2026國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯系我們 | 人才招聘 | 網站聲明 | 網站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
云南網警備案專用圖標
聯系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網
云南網警報警專用圖標
未满十八18勿进黄网站免费看