JavaScript-在函数回调之间共享值
我有一个来自外部JavaScript库的函数JavaScript-在函数回调之间共享值,javascript,callback,bind,Javascript,Callback,Bind,我有一个来自外部JavaScript库的函数foo(a,b,c) a、b和c是回调函数 在回调a中,我正在生成一个随机IDvar 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) ); 那么所有函
foo(a,b,c)
a
、b
和c
是回调函数
在回调a
中,我正在生成一个随机IDvar 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都应该能够通过这个.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>
功能Go(iCall)
{
var that={'that':this'id':-1,'call':iCall};
foo(a.bind(that),b.bind(that),c.bind(that));
}
函数foo(a、b、c)
{
setTimeout(a,Math.random()*3000);
setTimeout(b,Math.random()*3000);
setTimeout(c,Math.random()*3000);
}
函数a(){
如果(this.id<0)this.id=1;
日志(“a”,this.call,this.id);
}
函数b(){
如果(this.id<0)this.id=2;
日志(“b”,this.call,this.id);
}
函数c(){
如果(this.id<0)this.id=3;
日志(“c”,this.call,this.id);
}
功能日志(abc、呼叫、id){
document.getElementById(“log”).innerHTML+=“
”+数组(call.join(“\uuuuu”)+”:Go(“+call+”):“+abc+”)Id=“+Id;
}
Go(1);Go(2);Go(3);
请参见行动:是的,您可以这样做。只需在
foo
外部声明id
。当然,只需在a
和c
可访问的范围内定义id
。谢谢你的快速回答。你能分享一个闭包的例子吗?我不能忍受这个。@wI2L@Derek朕會功夫 我想我的需求应该是这样的:也许我的问题不清楚。无论如何,我尝试了这个方法,我得到了“id未定义”。我将尝试创建一个更复杂的JSFIDLE,使其更清晰。