JavaScript - 在函数回调之间共享值

标签 javascript callback bind

我有一个来自外部 JavaScript 库的函数 foo(a, b, c)

abc 是回调函数。

在回调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>

查看实际操作:https://jsfiddle.net/vw35bz3d/

关于JavaScript - 在函数回调之间共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769516/

相关文章:

javascript - 如何创建仅在同时按下两个 'shift + left/right arrow' 键后触发的事件监听器?

javascript - 对于多个页面,使用单个 requireJs 配置还是多个?

java - 为 Future 回调编写 junit 测试用例

javascript - jQuery Mobile——事件绑定(bind)

vb.net - 使用文本框搜索 datagridview 中的列 (vb.net)

javascript - 有什么方法可以绑定(bind)事件处理程序并同时调用它?

javascript - 动态创建带有嵌套对象/数组结构的数组的更好方法

javascript - Extjs - 在 Model.save() 中重试 API 请求

jquery - Greasemonkey + jQuery : using GM_setValue() within an event callback

php - 在 jQuery 中绑定(bind)事件的正确方法是什么?