javascript中bind函數的作用執行個體介紹,javascriptbind
<!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的bind
bind主要是為了改變函數內部的this指向,這個是在ECMA5以後加入的,所以IE8一下的瀏覽器不支援
bind方法會建立一個新函數,稱為綁定函數.當調用這個綁定函數時,綁定函數會以建立它時傳入bind方法的第一個參數作為this,傳入bind方法的第二個以及以後的參數加上綁定函數運行時本身的參數按照順序作為原函數的參數來調用原函數.
可以看這段執行個體:
var logger = { x: 0, updateCount: function(){ this.x++; console.log(this.x); }} // 下面兩段代碼的實現是一樣的 document.querySelector('button').addEventListener('click', function(){ logger.updateCount();}); //用這種方式讓代碼更簡潔,當然這隻是bind的一種情境document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));
javascript:對於Functionprototypebind()這個方法
Function.prototype.bind=function(thisArg){ var fn=this, slice=Array.prototype.slice, args=slice.call(arguments,1);//arguments1 var a1 = arguments; return function(){ alert(a1 == arguments);// 判斷是否為同一個 return fn.apply(thisArg,args.concat(slice.call(arguments)));//arguments2 }};((function(){}).bind())(2);// 總是alert出false不是。第一個arguments是只thisArg,第二個則是指返回的那個函數的arguments。
Function.prototype.bind=function(thisArg){ var fn=this, slice=Array.prototype.slice, args=slice.call(arguments,1);//arguments1 alert(arguments[0]);// alert出1 return function(){ alert(arguments[0]);// alert出2 return fn.apply(thisArg,args.concat(slice.call(arguments)));//arguments2 }};((function(){}).bind(1))(2);