我有一个来自外部 JavaScript 库的函数 foo(a, b, c)
。
a
、b
和 c
是回调函数。
在回调a
中,我生成一个随机ID var id
,我用它来引用具有id
属性的dom节点。是否可以从回调函数c
访问id
?
回调c
通常在foo
函数中的a
之后调用。
谢谢。
最佳答案
您不应在全局范围内定义 id,因为 foo 可能会被多次调用。尝试这样的事情:
var that = {'that' : this, 'id': 42};
foo(a.bind(that), b.bind(that), c.bind(that) );
那么所有函数 a、b、c 都应该能够通过 this.id 进行读/写 完整示例:
<html><body>
<div id="log"></div>
<script>
function Go(iCall)
{
var that = {'that' : this, 'id': -1, 'call' : iCall};
foo(a.bind(that), b.bind(that), c.bind(that) );
}
function foo(a,b,c)
{
window.setTimeout(a,Math.random()*3000);
window.setTimeout(b,Math.random()*3000);
window.setTimeout(c,Math.random()*3000);
}
function a(){
if (this.id < 0) this.id = 1;
Log("a",this.call,this.id);
}
function b(){
if (this.id < 0) this.id = 2;
Log("b",this.call,this.id);
}
function c(){
if (this.id < 0) this.id = 3;
Log("c",this.call,this.id);
}
function Log(abc,call,id){
document.getElementById("log").innerHTML += "<br/>"+Array(call).join("___")+" :Go("+call + "): "+abc+"() Id=" + id;
}
Go(1);Go(2);Go(3);
</script>
</body></html>
关于JavaScript - 在函数回调之间共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769516/