除了闭包,您还可以使用function.bind
:
google.maps.event.addListener(marker, 'click', change_selection.bind(null, i));
调用时将 in的值i
作为参数传递给函数。(null
用于绑定this
,在这种情况下您不需要。)
function.bind
由 Prototype 框架引入,并已在 ECMAScript 第五版中标准化。在浏览器都原生支持之前,您可以function.bind
使用闭包添加自己的支持:
if (!('bind' in Function.prototype)) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}