admin管理员组文章数量:1290099
I create a simple function node to demonstrate my problem:
var items=context.get('items');
if (items==undefined) { // first run
node.warn('Create items')
var items={'item1':100}
context.set('items',items)
return
}
items.item1+=1;
node.warn(items)
On each iteration, the variable is read from the context storage and incremented. It is NOT saved using context.set(...). Nevertheless, the variable keeps increasing. The type of context used does not matter.
I could not observe this behavior with simple variables, i.e., non-JSON types. Is this a bug or a feature?
What is the explanation for this behavior?
I create a simple function node to demonstrate my problem:
var items=context.get('items');
if (items==undefined) { // first run
node.warn('Create items')
var items={'item1':100}
context.set('items',items)
return
}
items.item1+=1;
node.warn(items)
On each iteration, the variable is read from the context storage and incremented. It is NOT saved using context.set(...). Nevertheless, the variable keeps increasing. The type of context used does not matter.
I could not observe this behavior with simple variables, i.e., non-JSON types. Is this a bug or a feature?
What is the explanation for this behavior?
Share Improve this question asked Feb 20 at 10:27 Gottfried PrandstetterGottfried Prandstetter 112 bronze badges1 Answer
Reset to default 0NodeJS is a pass by reference language, so when you do the context.get()
it does not return a copy of the object, it returns a reference to that object.
So the increment is not working on a local copy, it is working on the same object stored in the context.
It doesn't happen with a raw number, because that is not an object, but a primitive type.
This is working as intended.
This SO question covers what Pass by Reference means in more detail
What's the difference between passing by reference vs. passing by value?
本文标签: nodejsUnexpected behaviour of context itemsStack Overflow
版权声明:本文标题:node.js - Unexpected behaviour of context items - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741443994a2379084.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论