DIV CSS 佈局教程網

JavaScript bind 的作用與相容性實作
編輯:關於JavaScript     

bind 的主要用途,是建立一個新的函式,並固定其 this 指向。當事件處理或 callback 需要保持特定物件作為 this 時,bind 就非常有用。

基本範例

var button = document.getElementById("button");

button.onclick = function () {
  alert(this.id);
};

在這個例子中,this 指向 button。若我們希望 this 改為其他物件,就可以使用 bind。

var text = document.getElementById("text");
var button = document.getElementById("button");

button.onclick = function () {
  alert(this.id);
}.bind(text);

此時 this 不再指向 button,而是指向 text。

物件方法中的 bind

var obj = {
  color: "#ccc",
  element: document.getElementById("text"),
  events: function () {
    document.getElementById("button").addEventListener("click", function () {
      this.element.style.color = this.color;
    }.bind(this));

    return this;
  },
  init: function () {
    this.events();
  }
};

obj.init();

在事件監聽器中,this 預設可能指向觸發事件的元素。透過 bind(this),可以讓事件處理函式保持存取 obj 的能力。

舊版 IE 相容

IE6、IE7、IE8 不支援 Function.prototype.bind,可以自行擴充。

if (!Function.prototype.bind) {
  Function.prototype.bind = function (obj) {
    var slice = [].slice;
    var args = slice.call(arguments, 1);
    var self = this;
    var nop = function () {};
    var bound = function () {
      var context = this instanceof nop ? this : (obj ? obj : {});
      return self.apply(context, args.concat(slice.call(arguments)));
    };

    nop.prototype = self.prototype;
    bound.prototype = new nop();
    return bound;
  };
}

另外,Array.prototype.slice.call 常用來把類陣列物件轉成真正的陣列,例如 function 的 arguments。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved