您可以使用匿名函数和闭包。
function ReportPost(updateSpan, postID) {
if (confirm("Are you sure you want to report this post as spam or abuse?")) {
var proxy = SiteWS.ReportPost(
postID,
function(sender,e) {updateSpan.innerHTML = "Post reported" },
function(sender,e) {updateSpan.innerHTML = "An error occurred while reporting the post" }
);
}
}
编辑:
隐马尔可夫模型。。只是想知道,当调用匿名方法时,updateSpan会引用相同的范围吗?瓦利德·艾莎
是的,这就是闭包的魔力。试试这个小例子:
<head>
<script>
function foo()
{
bar(1, 100);
bar(2, 150);
bar(3, 200);
bar(4, 250);
bar(5, 300);
document.getElementById("div1").innerHTML += "foo() is done. ";
return;
}
function bar(val, timeout) {
window.setTimeout(
function() {
document.getElementById("div1").innerHTML += " " + val + " ";
},
timeout
);
}
</script>
</head>
<body>
<button onclick="foo()">click</button>
<div id="div1"></div>
</body>
您将看到,每次调用匿名函数时,它都会从调用bar()的时间/上下文中保留“自己的”val值。