如何同步访问 javascript 对象的私有成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10960531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to synchronize access to private members of a javascript object
提问by Shailesh Vaishampayan
I have a Javascript object created as follows:
我创建了一个 Javascript 对象,如下所示:
var ccStatTracker = (function (){
ccmap:{
"1":["1","2","3","4"],
"2":["4","5"];
}
return {
modifyCCMap: function (){
// Code which takes following actions:
// - adds/removes keys.
// - modifies arrays stored as values against the keys in the map.
}
}
)();
I have a DHTMLXGrid component which displays grid in the form of rows and columns. When I edit any cell in the grid, "onEditCell" event is called. Now, I want to call ccStatTracker.modifyCCMap() from an event handler function attached to "onEditCell" event. As I go on modifying the cells, this event will be called asynchronously which will in turn call a function "modifyCCMap" which will modify private member "CCMap" of my Javascript object. So the latest state of my CCMap as seen by two calls might be different right? So what is the best way to handle this? Is there something as "Synchronized" in Javascript as in Java?
我有一个 DHTMLXGrid 组件,它以行和列的形式显示网格。当我编辑网格中的任何单元格时,会调用“onEditCell”事件。现在,我想从附加到“onEditCell”事件的事件处理函数中调用 ccStatTracker.modifyCCMap()。当我继续修改单元格时,将异步调用此事件,该事件将依次调用函数“modifyCCMap”,该函数将修改我的 Javascript 对象的私有成员“CCMap”。因此,两次调用所看到的 CCMap 的最新状态可能不同,对吗?那么处理这个问题的最佳方法是什么?Javascript 中是否有与 Java 中“同步”的东西?
Please help me as it will determine the approach we want to take for implementing this.
请帮助我,因为这将决定我们要采取的实施方法。
回答by Tomasz Nurkiewicz
JavaScript is single-threaded (web-workers aside for a moment), nothing happens asynchronously(or everything for that matter) - all code: event handlers, timeouts, callbacks, etc. - run in the same thread, one after another.
JavaScript 是单线程的(网络工作者暂时搁置一旁),没有任何异步发生(或与此相关的所有事情) - 所有代码:事件处理程序、超时、回调等 - 在同一个线程中一个接一个地运行。
Thus you don't need any synchronization in JavaScript. Any given piece of code in JavaScript is guaranteed to be executed by only a single thread. How cool is that?
因此,您不需要在 JavaScript 中进行任何同步。JavaScript 中的任何给定代码都保证仅由单个线程执行。多么酷啊?
See also
也可以看看
- JavaScript equivalent of SwingUtilities.invokeLater()
- "atomic" operation desturbed by asynchronous ajax callbacks
- Are there any atomic javascript operations to deal with Ajax's asynchronous nature?
- how is async programming (promises) implemented in javascript? isn't javascript a ui-threaded environment?
- ...