可以使用bind
原型所存在的所有功能在現代瀏覽器
window.onload = function() {
var el = document.getElementsByClassName('modify');
for (var i = 0; i < el.length; i++) {
var getId=el[i].id.split("_");
document.getElementById("modify_y_"+getId[2]).addEventListener('mouseover', function(theid) {
document.getElementById("modify_x_"+getId[2]).style.borderBottom = '#e6665 solid 3px';
}.bind(null,getId[2]), false);
}
}
如果您需要支持沒有bind
nativly建在舊的瀏覽器,你可以使用這個poly-fill taken from MDN在那裏你會還對綁定的原型功能找到文檔
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
很常見的問題,這裏是一個解釋:http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example –
@MattGreer:使用閉包是多年來的最佳實踐,但是我們應該開始教人們使用'bind',因爲它是一種優秀的解決方案,並且很快將被內置到所有人們瞄準的瀏覽器中 –
@MartinJespersen酷,我沒有意識到你可以通過參數綁定。由於我們支持舊的IE,我仍然沒有使用過它。感謝您的高舉。 –