bind 可用來綁定函式的 this 指向,並可預先傳入部分參數。在舊環境不支援 bind 時,可以自己實作一個相容版本。
以下範例展示如何建立 bind,以及如何將物件方法綁定到特定 DOM 元素上。
Function.prototype.bind = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return self.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
};
var eleText = document.getElementById('text');
eleBtn.onclick = function (color) {
this.style.color = color;
}.bind(eleText, '#cd0000');