javascript中bind函數(shù)的作用實例介紹
更新時間:2014年09月28日 17:45:32 投稿:whsnow
bind()的方法在ie,6,7,8中不適用,需要擴展通過擴展Function prototype可以實現(xiàn)此方法,下面為大家介紹下javascript中bind函數(shù)的作用
<!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
此時會發(fā)現(xiàn)this改變?yōu)閠ext
函數(shù)字面量里也適用,目的是保持上下指向(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可以實現(xiàn)此方法。
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 );
將類似數(shù)組轉(zhuǎn)換為數(shù)組
您可能感興趣的文章:
- javascript中的Function.prototye.bind
- javascript之bind使用介紹
- js apply/call/caller/callee/bind使用方法與區(qū)別分析
- js bind 函數(shù) 使用閉包保存執(zhí)行上下文
- JavaScript中的prototype.bind()方法介紹
- js設置組合快捷鍵/tabindex功能的方法
- javascript bind綁定函數(shù)代碼
- 淺談javascript中call()、apply()、bind()的用法
- JS中改變this指向的方法(call和apply、bind)
- 深入理解JS中的Function.prototype.bind()方法
相關文章
將form表單中的元素轉(zhuǎn)換成對象的方法適用表單提交
這篇文章主要介紹了如何將form表單中的元素轉(zhuǎn)換成對象,需要的朋友可以參考下2014-05-05