DIV CSS 佈局教程網

Function.prototype.bind 的用法與相容性處理
編輯:關於JavaScript     

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');
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved