Javascript 意外地通过引用传递整数?
我对此有些问题。出于某种原因,Javascript 意外地通过引用传递整数?,javascript,jquery,Javascript,Jquery,我对此有些问题。出于某种原因,updateCurrentItem总是使用相同的参数调用,而不管是什么 function updatePromoList(query) { query = query.toUpperCase(); clearCurrentList(); var numItems = 0; currentItem = 0; result_set = cached[query.charAt(0)][query.charAt(1)][query.
updateCurrentItem
总是使用相同的参数调用,而不管是什么
function updatePromoList(query) {
query = query.toUpperCase();
clearCurrentList();
var numItems = 0;
currentItem = 0;
result_set = cached[query.charAt(0)][query.charAt(1)][query.charAt(2)];
for(i in result_set){
if(numItems >= NUMBER_MATCHES){
$("<li/>").html("<span style='color: #aaa'>Please try to limit your search results</span>").appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(numItems+1); });
break;
}
promo = result_set[i];
found_number = false;
if (!promo.client)
found_number = (promo.prj_number.toString().substr(0,query.length) == query) ? true : false;
if (query.length >= MATCH_NAME) {
if(promo.prj_name && typeof promo.prj_name == 'string'){
found_name = promo.prj_name.toUpperCase().indexOf(query);
} else {
found_name = -1;
}
if (promo.client)
found_client = promo.client_name.toString().indexOf(query);
else
found_client = -1;
} else {
found_name = -1;
found_client = -1;
}
if(found_client >= 0) {
var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.client_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); }); } else if(found_name >= 0 || found_number) { var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.prj_number+": "+promo.prj_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); });
}
if(found_number || found_client >= 0 || found_name >= 0){
numItems++;
}
}
}
function updateCurrentItem(i){
currentItem = i;
console.log("updating to", i);
}
然后,当我将鼠标移动到包含这些
s的内容区域上,并显示mouseOver
事件时,我所看到的是:
updating to 4
始终4。有什么想法吗?您正在创建一个闭包,但它仍然绑定到numItems变量:
function(event){ updateCurrentItem(numItems+1); }
你应该这样做:
(function(numItems){return function(event){ updateCurrentItem(numItems+1); }})(numItems)
编辑:我想我可能有错误的功能,但同样的原则适用:
function(event){ updateCurrentItem(thisIndex); }
应该是
(function(thisIndex)
{
return function(event){ updateCurrentItem(thisIndex); }
})(thisIndex)
你的代码似乎有效,但我仍然感到困惑。我认为如果我使用闭包,它将在创建闭包时获得变量的值,而不是对该变量的引用?不,JavaScript是一种后期绑定语言。讨论:。
(function(thisIndex)
{
return function(event){ updateCurrentItem(thisIndex); }
})(thisIndex)